Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中,如何在10个元素中找到最多2个元素的复杂性更低的元素?_Java - Fatal编程技术网

在java中,如何在10个元素中找到最多2个元素的复杂性更低的元素?

在java中,如何在10个元素中找到最多2个元素的复杂性更低的元素?,java,Java,你能告诉我如何在java中找到10个元素中的最大2个元素吗。 我确实喜欢这个,但它的复杂性太高了。我需要减少它 阿尔戈 take max=a[0] 对于(int i=0;imax) max=a[i] } 第二种方法是使用冒泡排序对数组进行排序,然后查找最后2个元素?max=a[0]; max =a[0]; max2 = a[0]; for(int i =0;i<10;i++) { if(a[i]>max) { max2=max; max

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

take max=a[0]
对于(int i=0;imax)
max=a[i]
}
第二种方法是使用冒泡排序对数组进行排序,然后查找最后2个元素?

max=a[0];
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];
   }
}
max2=a[0]; 对于(int i=0;imax) { max2=最大值; max=a[i]; 继续; } 如果(a[i]>max2 | | max2==max) { max2=a[i]; } }
这是您真正做到这一点的最快方法。。。还有,泡泡类?!?!真的吗?你可以使用
O(n log n)
中的mergesort/heapsort/quicksort对数组进行排序,然后获取数组的最后两个元素(
O(1)
),你可以从索引1开始循环,因为你已经用[0]@A4L初始化了max,这不会改变复杂性(仍然
O(n)
),而且他没有用[0],这只是为了初始化。=)@ZouZou我知道,但仍然保存了一个循环迭代:)-1我不在乎这是否正确,至少给OP一个机会让他自己弄清楚……没问题,情感投票仍然是投票……如果最大值存储在索引0中,您的代码就不起作用。是的,这是真的。只是编辑以处理这个问题大小写为+1表示不使用填鸭式喂食。保留最大值和第二个最大值的初始化是什么?最大值和第二个最大值的起始值是什么?如果用户需要第3个或第n个最大元素,该怎么办?QuickSelect算法可查找第k个最大值
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];
   }
}
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