Leetcode刷题——day2

414. 第三大的数

class Solution {
    public int thirdMax(int[] nums) {
        int n = nums.length;
        long first, second, third;
        first = second = third = Long.MIN_VALUE;

        if(n == 1) return nums[0];
        if(n == 2) return Math.max(nums[0], nums[1]);

        for(int i = 0; i < n; i++) {
            if(nums[i] == first || nums[i] == second) continue;
            if(nums[i] > first) {
                third = second;
                second = first;
                first = nums[i];
                continue;
            }
            if(nums[i] > second) {
                third = second;
                second = nums[i];
                continue;
            }
            if(nums[i] > third) {
                third = nums[i];
            }
        }
        return third == Long.MIN_VALUE ? (int)first : (int)third;
    }
}

628. 三个数的最大乘积

class Solution {
    public int maximumProduct(int[] nums) {
        int n = nums.length;
        int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE, max3 = Integer.MIN_VALUE;
        int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
        for(int x : nums) {
            if(x < min1) {
                min2 = min1;
                min1 = x;
            } else if(x < min2) {
                min2 = x;
            }

            if(x > max1) {
                max3 = max2;
                max2 = max1;
                max1 = x;
            } else if(x > max2) {
                max3 = max2;
                max2 = x;
            } else if(x > max3) {
                max3 = x;
            }
        }
        return Math.max((max1 * max2 * max3), (min1 * min2 * max1));
    }
}
posted @ 2021-08-31 22:25  来一块小饼干  阅读(23)  评论(0编辑  收藏  举报