Leetcode Third Maximum Number 414

来源:互联网 发布:pdf.js 无法显示字体 编辑:程序博客网 时间:2024/05/21 22:32

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.

题目链接

找到第三大的数字 时间复杂度是O(n)
考虑遍历三次:

但是会出现,其中出现最小数的情况,然后代码就跟别人不一样了。。。。

我考虑标记位置来纪录,因为位置不能是负数

class Solution {public:    int thirdMax(vector<int>& nums) {        int len=nums.size();        int maxnum=nums[0];        int maxpos=0;        for(int i=0;i<len;i++){            if(maxnum<nums[i]) {                maxnum=nums[i];                maxpos=i;            }        }        int second=INT_MIN;        int secpos=-1;        for(int i=0;i<len;i++){            if(nums[i]==maxnum) continue;            if(second<=nums[i]) {                second=nums[i];                secpos=i;            }        }        if(second==INT_MIN && secpos==-1) {            return maxnum;        }        int third=INT_MIN;        int thpos=-1;        for(int i=0;i<len;i++){            if(nums[i]==maxnum || nums[i]==second) continue;            if(third<=nums[i]) {                third=nums[i];                thpos=i;            }        }        return (third==INT_MIN && thpos==-1) ? maxnum:third;    }};

代码有点长,学习别人的:

class Solution {public:    int thirdMax(vector<int>& nums) {        long first = LONG_MIN, second = LONG_MIN, third = LONG_MIN;        for (int num : nums) {            if (num > first) {                third = second;                second = first;                first = num;            } else if (num > second && num < first) {                third = second;                second = num;            } else if (num > third && num < second) {                third = num;            }        }        return (third == LONG_MIN || third == second) ? first : third;    }};
0 0
原创粉丝点击