|
28 | 28 | */
|
29 | 29 | public class _414 {
|
30 | 30 |
|
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); |
40 | 35 | }
|
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); |
63 | 39 | }
|
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); |
67 | 43 | }
|
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); |
81 | 45 | }
|
82 | 46 |
|
83 | 47 | }
|
0 commit comments