|
| 1 | +package easy; |
| 2 | + |
| 3 | +public class ThirdMaximumNumber { |
| 4 | + |
| 5 | + public static int thirdMax_20161115(int[] nums) { |
| 6 | + |
| 7 | + if (nums == null || nums.length == 0) return 0; |
| 8 | + if (nums.length < 3) { |
| 9 | + int max = 0; |
| 10 | + for (int i : nums) { |
| 11 | + max = Math.max(i, max); |
| 12 | + } |
| 13 | + return max; |
| 14 | + } |
| 15 | + |
| 16 | + long first = Long.MIN_VALUE, second = Long.MIN_VALUE, third = Long.MIN_VALUE; |
| 17 | + |
| 18 | + for (int i = 0; i < nums.length; i++){ |
| 19 | + if (nums[i] > first) { |
| 20 | + long tmpFirst = first; |
| 21 | + first = nums[i]; |
| 22 | + |
| 23 | + long tmpSecond = second; |
| 24 | + second = tmpFirst; |
| 25 | + |
| 26 | + third = tmpSecond; |
| 27 | + } else if (nums[i] == first) continue; |
| 28 | + else if (nums[i] > second) { |
| 29 | + long tmpSecond = second; |
| 30 | + second = nums[i]; |
| 31 | + |
| 32 | + third = tmpSecond; |
| 33 | + } else if (nums[i] == second) continue; |
| 34 | + else if (nums[i] > third) { |
| 35 | + third = nums[i]; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if (third == Long.MIN_VALUE){ |
| 40 | + return (int) first; |
| 41 | + } |
| 42 | + |
| 43 | + return (int) third; |
| 44 | + |
| 45 | + } |
| 46 | + |
| 47 | + public static void main(String...strings){ |
| 48 | +// int[] nums = new int[]{1,2}; |
| 49 | +// int[] nums = new int[]{2,2,3,1}; |
| 50 | +// int[] nums = new int[]{1,1,2};//should be 2 |
| 51 | + int[] nums = new int[]{1,2,-2147483648};//should be -2147483648 |
| 52 | +// int[] nums = new int[]{3,2,1}; |
| 53 | +// System.out.println(thirdMax(nums)); |
| 54 | + System.out.println(thirdMax_20161115(nums)); |
| 55 | + } |
| 56 | + |
| 57 | +} |
0 commit comments