Skip to content

Commit 2750a1d

Browse files
committed
Time: 4 ms (61.70%) | Memory: 43.3 MB (53.13%) - LeetSync
1 parent 4c477ff commit 2750a1d

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed
Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
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);
2+
public int thirdMax(int[] arr) {
3+
Arrays.sort(arr);
4+
int n = arr.length;
5+
int count = 1;
6+
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+
}
712
}
813
}
9-
distinctNums.sort((a,b) -> - a.compareTo(b));
10-
return distinctNums.size() >= 3 ? distinctNums.get(2) : distinctNums.get(0);
14+
return arr[n - 1];
1115
}
1216
}

0 commit comments

Comments
 (0)