There was an error while loading. Please reload this page.
1 parent 4c477ff commit 2750a1dCopy full SHA for 2750a1d
414-third-maximum-number/third-maximum-number.java
@@ -1,12 +1,16 @@
1
class Solution {
2
- public int thirdMax(int[] nums) {
3
- List<Integer> distinctNums = new ArrayList<>();
4
- for (int num : nums) {
5
- if (!distinctNums.contains(num)) {
6
- distinctNums.add(num);
+ public int thirdMax(int[] arr) {
+ Arrays.sort(arr);
+ int n = arr.length;
+ int count = 1;
+ for (int i = n - 2; i >= 0; i--) {
7
+ if (arr[i] != arr[i + 1]) {
8
+ count++;
9
+ if (count == 3) {
10
+ return arr[i];
11
+ }
12
}
13
- distinctNums.sort((a,b) -> - a.compareTo(b));
- return distinctNums.size() >= 3 ? distinctNums.get(2) : distinctNums.get(0);
14
+ return arr[n - 1];
15
16
0 commit comments