-1

你能告诉我如何在 java 中找到 10 个元素中的最大 2 个元素吗?我确实喜欢这个,但它的复杂性太高了。我需要减少那个算法

take max =a[0]

for(int i =0;i<10;i++){

if(a[i]>max)
max=a[i]

}

第二种使用冒泡排序对数组进行排序然后找到最后 2 个元素的方法?

4

2 回答 2

2
Instead of sorting the array, you can simply do the following:
Keep a largestValue and a secondLargestValue
Loop through the entire array once, for each element:
Check to see if the current element is greater than largestValue:
If so, assign largestValue to secondLargestValue, then assign the current element to largestValue (think of it as shifting everything down by 1)
If not, check to see if the current element is greater than secondLargestValue
If so, assign the current element to secondLargestValue
If not, do nothing.
O(n) run time

O(1) space requirement
于 2013-11-02T17:11:07.217 回答
-1
max =a[0];
max2 = a[0];

for(int i =0;i<10;i++)
{

   if(a[i]>max)
   {   
      max2=max;
      max=a[i];
      continue;
   }
   if(a[i]>max2||max2==max)
   {
       max2=a[i];
   }
}
于 2013-11-02T17:10:16.920 回答