C/C++教程

Leetcode刷题——day2

本文主要是介绍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;
    }
}
这篇关于Leetcode刷题——day2的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!