Input:
nums = [3,2,1]
Output:
1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
Example 2:
1
2
3
4
5
6
7
8
Input:
nums = [1,2]
Output:
2
Explanation:
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.
Example 3:
1
2
3
4
5
6
7
8
Input:
nums = [2,2,3,1]
Output:
1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.
To find the third distinct maximum, we can keep track of the top three unique values as we scan the array. By updating these values only when we see a new, larger, or unique number, we ensure we always know the first, second, and third maximums. If there are fewer than three distinct numbers, we return the largest.
classSolution {
publicintthirdMax(int[] nums) {
Long max1 =null, max2 =null, max3 =null;
for (int n : nums) {
if (Objects.equals(max1, (long)n) || Objects.equals(max2, (long)n) || Objects.equals(max3, (long)n)) continue;
if (max1 ==null|| n > max1) {
max3 = max2; max2 = max1; max1 = (long)n;
} elseif (max2 ==null|| n > max2) {
max3 = max2; max2 = (long)n;
} elseif (max3 ==null|| n > max3) {
max3 = (long)n;
}
}
return max3 ==null? max1.intValue() : max3.intValue();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funthirdMax(nums: IntArray): Int {
var max1: Long? = nullvar max2: Long? = nullvar max3: Long? = nullfor (n in nums) {
val v = n.toLong()
if (v == max1 || v == max2 || v == max3) continuewhen {
max1 ==null|| v > max1 -> { max3 = max2; max2 = max1; max1 = v }
max2 ==null|| v > max2 -> { max3 = max2; max2 = v }
max3 ==null|| v > max3 -> { max3 = v }
}
}
returnif (max3 ==null) max1!!.toInt() else max3.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defthirdMax(self, nums: list[int]) -> int:
max1 = max2 = max3 =Nonefor n in nums:
if n == max1 or n == max2 or n == max3:
continueif max1 isNoneor n > max1:
max3, max2, max1 = max2, max1, n
elif max2 isNoneor n > max2:
max3, max2 = max2, n
elif max3 isNoneor n > max3:
max3 = n
return max1 if max3 isNoneelse max3