414. 第三大的数

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

示例 1:

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

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

输入:[2, 2, 3, 1]
输出:1
解释:注意,要求返回第三大的数,是指在所有不同数字中排第三大的数。
此例中存在两个值为 2 的数,它们都排第二。在所有不同数字中排第三大的数为 1 。
 

提示:

1 <= nums.length <= 104
-231 <= nums[i] <= 231 - 1
 

进阶:你能设计一个时间复杂度 O(n) 的解决方案吗?

冒泡排序O(n2):

分三种情况:

1、数组的长度没有达到3

2、数组的长度达到3,但是没有出现3个不同的数字

3、数组的长度达到3,且有3个不同大小的数字

class Solution {
    public int thirdMax(int[] nums) {
        for(int i=0;i<nums.length;i++){
            for(int j=1;j<nums.length-i;j++){
                if(nums[j-1]<nums[j]){
                    int temp = nums[j];
                    nums[j] = nums[j-1];
                    nums[j-1] = temp;
                }
            }
        }
        if(nums.length<3){
            return nums[0];
        }
        int sum = 1;
        for(int i=1;i<nums.length;i++){
            if(nums[i-1]>nums[i]){
                sum++;
            }
            if(sum==3){
                return nums[i];
            }
        }
        return nums[0];
    }
}

第二种进阶的解题方式,复杂度为O(n):

class Solution {
    private static final long LONG_MIN = (long)Integer.MIN_VALUE-1;
    public static int thirdMax(int[] nums) {
        if(nums.length==1) {
            return nums[0];
        }else if(nums.length==2){
            return Math.max(nums[0],nums[1]);
        }else {
            long max1 = LONG_MIN;
            long max2 = LONG_MIN;
            long max3 = LONG_MIN;
            int flag = 0;
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] > max1) {
                    max3 = max2;
                    max2 = max1;
                    max1 = nums[i];
                    flag++;
                } else if (nums[i] < max1 && nums[i] > max2) {
                    max3 = max2;
                    max2 = nums[i];
                    flag++;
                } else if (nums[i] < max2 && nums[i] > max3) {
                    max3 = nums[i];
                    flag++;
                }
            }
            return (int) (flag >= 3 ? max3 : max1);
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)

NUMS数组中最小的可取数字为2的31次方,即MIN_VALUE,所以需要将数字转换成LONG才可以进行计算。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值