对于给定的k值,查找包含线性时间

时间:2022-04-10 00:28:51

Given array A is unsorted.

给定数组A是无序的。

I want to know both approches, using sorting and without sorting.

我想知道两个方法,使用排序和不使用排序。

How it can be done using sorting in linear time?

如何用线性时间排序?

First I searched for all elemnts which are smaller than k, then I tried to find the relative distances among the elements that i found in first scan by taking a variable count such that I initialised the count with the index of first element I got.

首先,我搜索了比k小的所有元素,然后我尝试找到在第一次扫描中发现的元素之间的相对距离,这是一个变量计数,这样我就用我得到的第一个元素的索引初始化计数。

Then adding the relative distance of next element found. This is what I thought.

然后添加找到的下一个元素的相对距离。这就是我的想法。

I prefer java, however I am interested in approch.

我喜欢java,但我对批准感兴趣。

1 个解决方案

#1


0  

If I've interpreted the requirements correctly, ie.:

如果我把要求解释正确的话。

print smallest([6, 1, 5, 3, 2, 7], 4)   # [1, 5, 3, 2]
print smallest([6], 4)                  # []
print smallest([1, 2, 3, 4, 5], 4)      # [1, 2, 3, 4]
print smallest([6, 1, 2, 3, 4], 4)      # [1, 2, 3, 4]

then you can do this in sub-linear time by finding the first non-conforming element from each side:

然后你可以在次线性时间内找到每边的第一个不符合的元素:

def smallest(a, k):
    if len(a) == 0:
        return []

    i = 0
    j = len(a) - 1
    while i < len(a) and a[i] > k:
        i += 1

    while j >= 0 and a[j] > k:
        j -= 1

    return a[i:j+1]   # subarray starting at i and ending before j+1

#1


0  

If I've interpreted the requirements correctly, ie.:

如果我把要求解释正确的话。

print smallest([6, 1, 5, 3, 2, 7], 4)   # [1, 5, 3, 2]
print smallest([6], 4)                  # []
print smallest([1, 2, 3, 4, 5], 4)      # [1, 2, 3, 4]
print smallest([6, 1, 2, 3, 4], 4)      # [1, 2, 3, 4]

then you can do this in sub-linear time by finding the first non-conforming element from each side:

然后你可以在次线性时间内找到每边的第一个不符合的元素:

def smallest(a, k):
    if len(a) == 0:
        return []

    i = 0
    j = len(a) - 1
    while i < len(a) and a[i] > k:
        i += 1

    while j >= 0 and a[j] > k:
        j -= 1

    return a[i:j+1]   # subarray starting at i and ending before j+1