๐ŸŒ• 414. ็ฌฌไธ‰ๅคง็š„ๆ•ฐ

ๅžไฝ›็ซฅๅญ2022ๅนด10ๆœˆ10ๆ—ฅ
  • algorithm
  • Number
ๅฐไบŽ 1 ๅˆ†้’Ÿ

๐ŸŒ• 414. ็ฌฌไธ‰ๅคง็š„ๆ•ฐ

้šพๅบฆ: ๐ŸŒ•

้—ฎ้ข˜ๆ่ฟฐ

img_5.png


่งฃๆณ•

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;
    }
}

่พ“ๅ‡บ

img_4.png

ไธŠๆฌก็ผ–่พ‘ไบŽ: 2022/10/10 ไธ‹ๅˆ8:43:48
่ดก็Œฎ่€…: liuxianzhishou