找到第二高实际上很简单:
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如果数组中至少有2个元素,它将返回。
Integer.MIN_VALUE如果数组仅包含相同的数字,它也将返回。



