LeetCode每日一题:第三大的数(No.414)

800 阅读2分钟

题目:第三大的数


给定一个非空数组,返回此数组中第三大的数。
如果不存在,则返回数组中最大的数。

示例:


输入: [3, 2, 1]
输出: 1
解释: 第三大的数是 1.

输入: [1, 2]
输出: 2
解释: 第三大的数不存在, 所以返回最大的数 2 .

输入: [2, 2, 3, 1]
输出: 1
解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。
存在两个值为2的数,它们都排第二。

思考:


定义三个Integer对象max1,max2,max3来记录前三大的数,默认为null。
遍历数组,进行比较。
如果max1为空或者当前元素大于max1,说明当前元素是最大元素,则将原先的max2赋值给max3.max1赋给max2,当前元素赋给max1。
如果max1不为空且当前元素不大于max1,再比较,如果max2为空或者当前元素大于max2小于max1,说明当前元素是第二大元素。
所以将原max2赋给max3,当前元素赋值给max2。
如果max2不为空且当前元素不大于max2小于max1,再比较,如果max3为空或者当前元素大于max3小于max2(这里要先判断下max2不为空,防止出现重复元素时报错),就将当前元素赋值给max3。
最后判断max3是否为null,不为null返回max3,null则返回max1。

实现:


class Solution {
    public int thirdMax(int[] nums) {
        if (nums.length == 1) {
            return nums[0];
        }
        if (nums.length == 2) {
            return Math.max(nums[0], nums[1]);
        }
        Integer max1 = null;
        Integer max2 = null;
        Integer max3 = null;
        for (int count = 0; count < nums.length; count++) {
            if (max1 == null || (nums[count] > max1)) {
                max3 = max2;
                max2 = max1;
                max1 = nums[count];
            } else if ((max2 == null || nums[count] > max2) && nums[count] < max1) {
                max3 = max2;
                max2 = nums[count];
            } else if ((max3 == null || nums[count] > max3) && max2 != null && nums[count] < max2) {
                max3 = nums[count];
            }
        }
        return max3 != null ? max3 : max1;
    }
}