Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 3a65dc8

Browse files
edit 414
1 parent 419e173 commit 3a65dc8

File tree

1 file changed

+11
-47
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+11
-47
lines changed

src/main/java/com/fishercoder/solutions/_414.java

Lines changed: 11 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -28,56 +28,20 @@
2828
*/
2929
public class _414 {
3030

31-
public static int thirdMax(int[] nums) {
32-
33-
if (nums == null || nums.length == 0) return 0;
34-
if (nums.length < 3) {
35-
int max = 0;
36-
for (int i : nums) {
37-
max = Math.max(i, max);
38-
}
39-
return max;
31+
public int thirdMax(int[] nums) {
32+
long max1 = Long.MIN_VALUE, max2 = Long.MIN_VALUE, max3 = Long.MIN_VALUE;
33+
for (int i : nums) {
34+
max1 = Math.max(max1, i);
4035
}
41-
42-
long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE;
43-
44-
for (int i = 0; i < nums.length; i++){
45-
if (nums[i] > first) {
46-
long tmpFirst = first;
47-
first = nums[i];
48-
49-
long tmpSecond = second;
50-
second = tmpFirst;
51-
52-
third = tmpSecond;
53-
} else if (nums[i] == first) continue;
54-
else if (nums[i] > second) {
55-
long tmpSecond = second;
56-
second = nums[i];
57-
58-
third = tmpSecond;
59-
} else if (nums[i] == second) continue;
60-
else if (nums[i] > third) {
61-
third = nums[i];
62-
}
36+
for (int i : nums) {
37+
if (i == max1) continue;
38+
max2 = Math.max(max2, i);
6339
}
64-
65-
if (third == Long.MIN_VALUE){
66-
return (int) first;
40+
for (int i : nums) {
41+
if (i == max1 || i == max2) continue;
42+
max3 = Math.max(max3, i);
6743
}
68-
69-
return (int) third;
70-
71-
}
72-
73-
public static void main(String...strings){
74-
// int[] nums = new int[]{1,2};
75-
// int[] nums = new int[]{2,2,3,1};
76-
// int[] nums = new int[]{1,1,2};//should be 2
77-
int[] nums = new int[]{1,2,-2147483648};//should be -2147483648
78-
// int[] nums = new int[]{3,2,1};
79-
// System.out.println(thirdMax(nums));
80-
System.out.println(thirdMax(nums));
44+
return (int) (max3 == Long.MIN_VALUE ? max1 : max3);
8145
}
8246

8347
}

0 commit comments

Comments
 (0)