在Java中找到数组中第二大的数字

38
我很难理解在数组中找到第二大的数字的方法背后的逻辑。所使用的方法是找到数组中最大的数字,但要小于之前已经找到的最大数字。我仍然无法弄清楚的是为什么需要 `|| highest_score == second_highest`。例如,我输入了三个数字:98、56、3。如果没有这个条件,最大值和第二大值都将是98。请解释一下。
int second highest = score[0];  
if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)   
    second_highest = score[i];

你的代码片段没有说明highest_score是如何初始化的。 - Martin OConnor
3
"second highest" 应该改成 "second_highest" 吗?有循环吗? - trashgod
非常相似的线程:https://dev59.com/kkrSa4cB1Zd3GeqPXYwD 和 https://dev59.com/80nSa4cB1Zd3GeqPM1Br - Alexandros Gezerlis
45个回答

42

我不确定你所做的是否解决了问题;我认为这只是掩盖了你逻辑中的另一个问题。实际上,要找到第二大的很简单:

 static int secondHighest(int... nums) {
    int high1 = Integer.MIN_VALUE;
    int high2 = Integer.MIN_VALUE;
    for (int num : nums) {
      if (num > high1) {
        high2 = high1;
        high1 = num;
      } else if (num > high2) {
        high2 = num;
      }
    }
    return high2;
 }

这个算法可以在一遍内完成,时间复杂度为O(N)。如果你想接受并列的情况,那么将条件改为if (num >= high1),但是现在这样做的话,如果数组中没有至少两个元素,它将返回Integer.MIN_VALUE。如果数组只包含相同的数字,它也会返回Integer.MIN_VALUE


12
给定数组[2,2,1],返回的结果是2。这不对吗? - loc
1
"else if (num > high2)" 的检查应该改为 "else if (num != high1 && num > high2)"。 - Jhabar

16
// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;

// Loop over the array
for (int i = 0; i < array.Length; i++) {

    // If we've found a new highest number...
    if (array[i] > highest) {

        // ...shift the current highest number to second highest
        secondHighest = highest;

        // ...and set the new highest.
        highest = array[i];
    } else if (array[i] > secondHighest)
        // Just replace the second highest
        secondHighest = array[i];
    }
}

// After exiting the loop, secondHighest now represents the second
// largest value in the array

编辑:

哎呀,谢谢大家指出我的错误。现在已经修复了。


3
该代码无法处理当前元素超过第二高的值但不是最高值的情况。 - Anthony Pegram
这在像 {1, 0} 这样的输入上失败了。 - polygenelubricants
超级棒...我喜欢这个逻辑。你能告诉我第三大的是什么吗? - hitesh141
2
@hitesh - 这是讽刺吗?OP 没有问第三大的问题。如果他/她想要第n大的话,算法显然会不同。 - Scott Smith

5
如果初始设置为第二高的元素已经是最高的元素,则在找到下一个元素时应将其重新分配给新元素。也就是说,它被初始化为98,应该设置为56。但是,如果您不进行检查,56不比98高,因此不会设置。
如果最高数字出现两次,这将导致第二高的值,而不是如果您对数组进行排序所找到的第二个元素。

1
+1 是指出此代码返回的是第二高的值,而不是元素本身。 - Arkku

4
let array = [0,12,74,26,82,176,189,8,55,3,189]; 
let highest=0 ;
let secondHighest = 0;
for (let i = 0; i < array.length; i++) { 
if (array[i] > highest) { 
    // ...shift the current highest number to second highest
    secondHighest = highest; 
    // ...and set the new highest.
    highest = array[i]; 
} else if (highest > array[i] > secondHighest) { 
   // Just replace the second highest
   secondHighest = array[i]; 
  }
}
console.log(secondHighest);

enter image description here


7
请尽量避免仅仅把代码作为答案并尝试解释它的作用和原因。你的代码对于没有相关编程经验的人可能不明显。 - Frits

3

如果存在两个相同的最大数,那么我看到的答案是不适用的,就像下面的例子一样。

        int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
        SortedSet<Integer> set = new TreeSet<Integer>();
        for (int i: randomIntegers) {
            set.add(i);
        }
        // Remove the maximum value; print the largest remaining item
        set.remove(set.last());
        System.out.println(set.last());

我已将其从Set中移除,而不是从数组中移除


2

我的想法是假设数组的第一个和第二个成员是你的第一个最大值和第二个最大值。然后,你需要将数组的每个新成员与第二个最大值进行比较。不要忘记将第二个最大值与第一个最大值进行比较。如果它更大,就交换它们。

   public static int getMax22(int[] arr){
    int max1 = arr[0];
    int max2 = arr[1];
    for (int i = 2; i < arr.length; i++){
        if (arr[i] > max2)
        {
            max2 = arr[i];
        }

        if (max2 > max1)
        {
            int temp = max1;
            max1 = max2;
            max2 = temp;
        }
    }
     return max2;
}

1

数组中第二大的元素: 在Java中:

class test2{
    public static void main(String[] args) {

int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
int aa = a[a.length -2 ];
System.out.println(aa);


    }//main

}//end

在Python中:

a = [1, 2, 3, 9, 5, 7, 6, 4, 8]

aa = sorted(list(a))
print(aa)
aaa = aa[-2]
print(aaa)

1

导入 java.util.Scanner 包;

public class SecondHighestFromArrayTest{

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter size of Array");
    int size = scan.nextInt();
    int[] arr = new int[size];
    for (int i = 0; i < size; i++) {
        arr[i] = scan.nextInt();
    }
    System.out.println("second highest element " + getSecondHighest(arr));
}

public static int getSecondHighest(int arr[]) {
    int firstHighest = arr[0];
    int secondHighest = arr[0];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > firstHighest) {
            secondHighest = firstHighest;
            firstHighest = arr[i];
        } else if (arr[i] > secondHighest) {
            secondHighest = arr[i];
        }
    }
    return secondHighest;
}

}


1
 public static int secondLargest(int[] input) {
            int largest,secondLargest;

            if(input[0] > input[1]) {
                largest = input[0];
                secondLargest = input[1];
            }
            else {
                largest = input[1];
                secondLargest = input[0];
            }

            for(int i = 2; i < input.length; i++) {
                if((input[i] <= largest) && input[i] > secondLargest) {
                    secondLargest = input[i];
                }

                if(input[i] > largest) {
                    secondLargest = largest;
                    largest = input[i];
                }
            }

            return secondLargest;
        }

0
请尝试这个方法:通过使用这种方法,即使数组中包含随机数字,您也可以找到第二大的数字。第一个循环用于解决如果最大的数字出现在数组的第一个索引的问题。
public class secondLargestnum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] array = new int[6];
        array[0] = 10;
        array[1] = 80;
        array[2] = 5;
        array[3] = 6;
        array[4] = 50;
        array[5] = 60;
        int tem = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[0]>array[i]) {
                tem = array[0];
            array[0] = array[array.length-1];
            array[array.length-1] = tem;
            }
        }
        Integer largest = array[0];
        Integer second_largest = array[0];

        for (int i = 0; i < array.length; i++) {

            if (largest<array[i]) {
                second_large = largest;
                largest = array[i];
            }
            else if (second_large<array[i]) {
                second_large = array[i];

            }

        }
System.out.println("largest number "+largest+" and second largest number "+second_largest);

    }

}

2
请添加更多信息。仅包含代码和“尝试这个”答案是不被鼓励的(因为它们不包含可搜索的内容,也没有解释为什么应该“尝试这个”)。我们在这里努力成为知识资源。 - Mogsdad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接