leetcode 414. 第三大的数(Third Maximum Number)

题目描述:

给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。

示例 1:

    输入: [3, 2, 1]

    输出: 1

    解释: 第三大的数是 1.

示例 2:

    输入: [1, 2]

    输出: 2

    解释: 第三大的数不存在, 所以返回最大的数 2 .

示例 3:

    输入: [2, 2, 3, 1]

    输出: 1

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

解法:

class Solution {
public:
    
    void swap(int & a, int & b){
        a ^= b;
        b ^= a;
        a ^= b;
    }
    
    int thirdMax(vector<int>& nums) {
        int sz = nums.size();
        if(sz == 1){
            return nums[0];
        }else if(sz == 2){
            return max(nums[0], nums[1]);
        }
        int a = nums[0];
        int b = 0;
        int c = 0;
        bool second = false;    // the second biggest number has found
        bool third = false;     // the third biggest number has found
        
        for(int i = 1; i < sz; i++){
            // cout<<a<<", "<<b<<", "<<c<<endl;
            if(a == nums[i]){
                continue;
            }else if(a < nums[i]){
                if(second == false){
                    b = a;
                    a = nums[i];
                    second = true;
                }else{
                    c = b;
                    b = a;
                    a = nums[i];
                    third = true;
                }  
            }else{
                if(second == false){
                    b = nums[i];
                    second = true;
                }else{
                    if(nums[i] == b){
                        continue;
                    }else if(nums[i] > b){
                        third = true;
                        c = b;
                        b = nums[i];
                    }else{
                        if(third == false){
                            third = true;
                            c = nums[i];
                        }else{
                            c = max(c, nums[i]);
                        }
                    }
                }
            }
        }
        if(third == true){
            return c;
        }else{
            return a;
        }
    }
};
posted @ 2019-03-22 15:00  zhanzq1  阅读(164)  评论(0)    收藏  举报