LeetCode 题解 | 414. 第三大的数(线性扫描 C++)

写在前面:我写博客主要是为了对知识点的总结、回顾和思考,把每篇博客写得通俗易懂 是我的目标,因为能让别人看懂,才是真的学会了

从Math到CS的跨专业经历,让我格外珍惜学习时间,更加虚心好学,而分享技术和知识是快乐 的,非常欢迎大家和我一起交流学习,期待与您的进一步交流

题目描述

原题链接
在这里插入图片描述

算法

(线性扫描) O ( n ) O(n)

  • 遍历一遍数组,维护第一大的数,第二大的数和第三大的数
  • 注意:不需要记录已经出现在前三的数(去重);另外有个样例很坑[1,2,-2147483648],很多人都在这卡了,其实用long long去设初值就可以了

时间复杂度是 O ( n ) O(n) ,空间复杂度是 O ( 1 ) O(1)

代码

class Solution {
public:
    typedef long long LL;
    static const LL INF = 2 * 1.0 * INT_MAX;

    // Time complexity O(n)
    int thirdMax(vector<int>& nums) {
        int n = nums.size();
        LL rmax1 = -INF, rmax2 = -INF, rmax3 = -INF;

        // Traverse once 
        for (int i = 0; i < n; i ++) {
            LL t = nums[i];
            // Remove duplicates
            if (t == rmax1 || t == rmax2 || t == rmax3) continue;
            if (t > rmax1) {
                rmax3 = rmax2;
                rmax2 = rmax1;
                rmax1 = t;
            } else if (t > rmax2) {
                rmax3 = rmax2;
                rmax2 = t;
            } else if (t > rmax3) {
                rmax3 = t;
            }
        }    
        
        if (rmax3 == -INF) return rmax1;
        return rmax3;
    }
};
发布了239 篇原创文章 · 获赞 80 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_43827595/article/details/104253905