-1

Java で複雑さの少ない 10 要素で最大 2 要素を見つける方法を教えてください。私はこれが好きですが、複雑さが高すぎます。そのアルゴリズムを減らす必要があります

take max =a[0]

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

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

}

バブルソートを使用して配列をソートし、最後の2つの要素を見つける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 に答える