414. Third Maximum Number

来源:互联网 发布:企业数据安全 编辑:程序博客网 时间:2024/05/12 01:38

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: 1Explanation: The third maximum is 1.

Example 2:

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

Example 3:

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

用三个变量,分别记录最大值,第二大值和第三大值,在一次遍历过程中不断更新。还有,注意处理边界值-2147483648。

class Solution {public:    int thirdMax(vector<int>& nums) {        int firstMax = -2147483648;        int secondMax = -2147483648;        int thirdMax = -2147483648;        int i;        int count = 0;        bool flag = false;        for(i = 0; i < nums.size(); i ++){            if(firstMax < nums[i]){                thirdMax = secondMax;                secondMax = firstMax;                firstMax = nums[i];                count ++;            }else if(secondMax < nums[i] && firstMax != nums[i]){                thirdMax = secondMax;                secondMax = nums[i];                count ++;            }else if(thirdMax < nums[i] && firstMax != nums[i] && secondMax != nums[i]){                thirdMax = nums[i];                count ++;            }else if(nums[i] == -2147483648 && count < 3 && !flag){                count ++;                flag = true;            }        }        if(count >= 3) return thirdMax;        return firstMax;    }};


0 0
原创粉丝点击