zoukankan      html  css  js  c++  java
  • 414. Third Maximum Number

    Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in (O(n)).

    Example 1:

    Input: [3, 2, 1]
    
    Output: 1
    
    Explanation: The third maximum is 1.
    

    Example 2:

    Input: [1, 2]
    
    Output: 2
    
    Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
    

    Example 3:

    Input: [2, 2, 3, 1]
    
    Output: 1
    
    Explanation: Note that the third maximum here means the third maximum distinct number.
    Both numbers with value 2 are both considered as second maximum.
    

    自己的笨方法, 粗暴, 易理解, 且符合题目要求:

    使用了set.
    
    扫描三遍数组:
    第一遍: 找出max, 并依次把每个元素送入set, 若 set.size() < 3, 返回max;
    第二遍找出sec, 第三遍找出third;
    返回 third.
    

    (O(n)) time, (O(n)) extra space.

    int thirdMax(vector<int>& A) {
        int i, n = A.size();
        int max = INT_MIN, sec = INT_MIN, third = INT_MIN;
        set<int> set;
    
        for (i = 0; i < n; i++) {
            set.insert(A[i]);
            max = max > A[i] ? max : A[i];
        }
    
        if (set.size() < 3) return max;
    
        for (i = 0; i < n; i++)
            if (A[i] != max)
                sec = sec > A[i] ? sec : A[i];
    
        for (i = 0; i < n; i++)
            if (A[i] != max && A[i] != sec)
                third = third > A[i] ? third : A[i];
    
        return third;
    }
    

    人家的精巧方法:
    用到set, set.erase(), set.begin(), set.rbegin()
    set 默认升序. set.rbegin()表示最后一个元素的迭代器(指针).
    (O(n)) time, (O(n)) extra space.

    int thirdMax(vector<int>& A) {
        set<int> top3;
        for (int i = 0; i < A.size(); i++) {
            top3.insert(A[i]);
            // set 默认按 key 升序排序
            if (top3.size() > 3) top3.erase(top3.begin());
        }
        return top3.size() == 3 ? *top3.begin() : *top3.rbegin();
    }
    
  • 相关阅读:
    java从基础知识(九)I/O
    c++学习笔记(2)类的声名与实现的分离及内联函数
    转:给C++初学者的50个忠告
    c++学习(1)
    vim下缩进及高亮设置
    转载:c++ sort用法
    菜鸟成长记1,软件工程大一经历
    linux下挂载另一系统硬盘。
    OpenCV VideoCapture.get()参数详解
    opencv+python 添加文字 cv2.putText
  • 原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7358716.html
Copyright © 2011-2022 走看看