如何在Java中找到数组中最高和第二最高值的位置

时间:2019-10-31 18:45:26

标签: java

让我们假设我们有一个整数数组。例如 perimeter = {180,50,65,78,90,5,150,2,35},我想找到最大值及其在数组中的位置以及第二值及其在数组中的位置。

public class FindTopTwo {

public static void main(String[] args) {
    double perimeter[]= {180,50,65,78,90,5,150,2,35};
    double megisto, megisto2;
    int i;
    megisto=perimeter[0];
    megisto2=perimeter[0];
    for (i=0;i<perimeter.length;i++) {
        if (perimeter[i]>megisto) {
            megisto2=megisto;
            megisto=perimeter[i];}
        else if (perimeter[i]>megisto2) {
            megisto2=perimeter[i];
        }
    }
    System.out.println("the first is:"+megisto+"the second highest value is "+megisto2);    

   }

}

2 个答案:

答案 0 :(得分:0)

只需跟踪其索引(i)随着它们的值更改就可以:

public static void main(String[] args) {
    double perimeter[]= {180,50,65,78,90,5,150,2,35};
    double megisto, megisto2;
    megisto=perimeter[0];
    int megistoIndex = 0;

    megisto2=perimeter[0];

    int megisto2Index = 0;

    for (int i=0;i<perimeter.length;i++) {
        if (perimeter[i]>megisto) {
          megistoIndex = i;
          megisto = perimeter[i];
        } else if (perimeter[i] < megisto && perimeter[i] > megisto2) {
          megisto2Index = i;
          megisto2 = perimeter[i];
        }

    }
    System.out.println(String.format("the first is: %d at index %d. The second highest value is %d at index %d", megisto, megistoIndex, megisto2, megisto2Index));
}

答案 1 :(得分:0)

set highestIndex = -1;
set nextHighestIndex = -1;

for every element of perimiter:

  if highestIndex = -1:
    set highestIndex = i;
  else if perimiter[i] > perimiter[highestIndex]
    set nextHighestIndex = highestIndex;
    set highestIndex = i;
  else if perimiter[i] > perimieter[nextHighestIndex]
    set nextHighestIndex = i;

如果数组不为空,则将在以下位置找到最大值     允许者[highestIndex]

如果数组具有至少两个不同的值,则将在     周长[nextHighestIndex]