思路:
从前向后遍历,用三个变量first second third 保存前三个大的数,初值设为long类型的无穷小(因为开始提交到案遇到负的临界值的情况),如果新来的数大于first则 second first依次后移并且把这歌新值赋值给first
【正确代码】
1 class Solution { 2 public int thirdMax(int[] nums) { 3 long first = nums[0], second = Long.MIN_VALUE, third = Long.MIN_VALUE; 4 if (nums.length == 1) { 5 return (int)nums[0]; 6 } 7 if (nums.length == 2) { 8 return nums[0] > nums[1] ? (int)nums[0] : (int)nums[1]; 9 } 10 int count = 0; 11 for (int i = 1; i < nums.length; i++) { 12 if (nums[i] > first) { 13 third = second; 14 second = first; 15 first = nums[i]; 16 }else if (nums[i] > second && nums[i] < first) { 17 third = second; 18 second = nums[i]; 19 }else if (nums[i] < second && nums[i] > third) { 20 third = nums[i]; 21 }else { 22 continue; 23 } 24 count++; 25 } 26 if (count < 2) { 27 return (int)first; 28 } 29 return (int)third; 30 } 31 }
有时间想想用treeset的容器做一下。
时间: 2024-10-05 04:26:04