๐ 414. ็ฌฌไธๅคง็ๆฐ
2022ๅนด10ๆ10ๆฅ
- algorithm
๐ 414. ็ฌฌไธๅคง็ๆฐ
้พๅบฆ: ๐
้ฎ้ขๆ่ฟฐ
่งฃๆณ
class Solution {
public int thirdMax(int[] nums) {
// ๆ่ทฏ๏ผ
// ้ๅ๏ผ็กฎๅฎ first, second, third ๅ้
int len = nums.length;
if(len < 3) {
int res = nums[0];
for(int i = 1; i < len; i ++) {
res = Math.max(res, nums[i]);
}
return res;
}
// len >= 3
Integer first = nums[0]; // ่ฟ็จ ๅ
่ฃ
็ฑป ๅฏไปฅๅคๆญๅ้ๆฏๅฆๅทฒ็ป่ขซ่ตๅผ
Integer second = null;
Integer third = null;
for(int i = 0; i < len; i ++) {
if(first == null || nums[i] > first) {
// ๆดไฝๅ็งป
third = second;
second = first;
first = nums[i];
} else if(nums[i] < first && (second == null || nums[i] > second)) {
third = second;
second = nums[i];
} else if((second != null && nums[i] < second) && (third == null || nums[i] > third)) {
third = nums[i];
}
}
return (third == null) ? first: third;
}
}