簡體   English   中英

復雜度為O(n)的數組中第二高的數字

[英]second highest number in array with O(n) complexity

給定一個數組,我們如何才能找到O(n)復雜度第二高的數字,使用排序技術,我可以獲得的最佳復雜度是O(nlogn) 如何獲得O(n)時間復雜度?

這是一個簡單的線性解決方案:

firstMax = max(a[0], a[1])
secondMax = min(a[0], a[1])
for elem in a:
    if elem >= firstMax:
        secondMax = firstMax
        firstMax = elem
    else if elem > secondMax:
        secondMax = elem
print(secondMax)
#Here is a simple solution in o(n) complexity


array =[]

puts "enter the size of array"

sizeOfArray  = gets.chomp.to_i

sizeOfArray.times do
        array << gets.chomp.to_i
end

if array[0] > array[1]
        highest = array[0]
        second_highest = array[1]
else
        highest = array[1]
        second_highest = array[0]
end


for i in 2..array.size - 1
        if array[i] > highest
                second_highest = highest
                highest = array[i]
        end

        if (array[i]< highest) && (array[i] > second_highest)
                second_highest = array[i]
        end
end

puts highest
puts second_highest

遍歷所有數組中的所有“ n”個元素,並保持前兩個最高的否。

Assume a[], b[] and c[] are the arrays.


first_highest = a[0];
second_highest = a[1];

for (all elements in a[], b[] and c[]) {
    if (element > first_highest) {
        first_highest = element;
    } else if (element > second_highest) {
        second_highest = element;
    }
}

您可以使用QuickSelect在O(n)中輕松完成此操作。

QuickSortSelection(numbers, currentLength, k) {
    if (currentLength == 1)
      return numbers[0];
    int pivot = random number from numbers array;

int newPivotIndex = partitionAroundPivot(numbers) // check quicksort algorithm for more details - less elements go left to the pivot, bigger elements go right

if ( k == newPivotIndex )
    return pivot;
else if ( k < newPivotIndex )
    return QuickSortSelection(numbers[0..newPivotIndex-1], newPivotIndex, k)
else
   return QuickSortSelection(numbers[newPivotIndex+1..end], currentLength-newPivotIndex+1, k-newPivotIndex);
}

看看我的答案: 部分選擇排序與合並排序一起找到“數組中最大的k”

我不確定您在這里要問什么:您說給定了一個數組列表。 如果您的意思是說您有一個數組並且想找到第二大的元素,那么您可以簡單地在第一遍中找到最高的編號,在第二遍中找到第二高的編號。 這需要O(n)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM