414. Third Maximum Number(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83824977

题目:

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.

解释:
返回数组中的最大的第三个数,需要注意的是,如果数组的长度小于3,直接返回最大的数就好,如果数组的长度刚好等于3,直接返回最小的数就好。注意,重复的数字当成一个数字看。所以需要先set()一下。
python代码:

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums=set(nums)
        len_nums=len(nums)
        if len_nums<3:
            return max(nums)
        if len_nums==3:
            return min(nums)
        nums.remove(max(nums))
        nums.remove(max(nums))
        return max(nums)

上面代码的速度略慢,因为每次都要max()remove(),下面是一个略快的代码:
python代码:

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        set_nums=set(nums)
        len_set_nums=len(set_nums)
        max_num=max(nums)
        min_num=min(nums)
        if len_set_nums<3:
            return max_num
        if len_set_nums==3:
            return min_num
        else:
            first_max=max_num
            second_max=float('-inf')
            third_max=float('-inf')
            for num in set_nums:
                if num>second_max and num<first_max:
                    second_max,third_max=num,second_max
                elif num>third_max and num<second_max:
                    third_max=num
            return third_max     

c++代码:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int>_set(nums.begin(),nums.end());
        int len_set=_set.size();
        auto minmax=minmax_element(_set.begin(),_set.end());
        int min_num=*minmax.first;
        int max_num=*minmax.second;
        if(len_set<3)
            return max_num;
        else if(len_set==3)
            return min_num;
        else
        {
            int second_max=INT_MIN;
            int third_max=INT_MIN;
            for(auto num:_set)
            {
                if (num>second_max &&num<max_num)
                {
                    third_max=second_max;
                    second_max=num; 
                }
                else if(num>third_max &&num<second_max)
                    third_max=num;
            }
            return third_max;
        }
    }
};

总结:
突然发现,stl的set是排好序的,所以在c++中可以用set()做,维护一个长度为3的set(),每次都insert(),当size()>3以后则erase()第一个,如果最后set的长度等于3,则返回第一个元素(最小的那个),如果小于3,则返回最后的那个(rbegin(),证明原数组中不同的数字的个数不到3个,最大的那个 )。主要还是利用了stl set顺序的特性。
代码如下:

#include <set>
using namespace std;
class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int>_set;
        for(auto num:nums)
        {
            _set.insert(num);
            while(_set.size()>3)
                _set.erase(_set.begin());
        }
        return (_set.size()==3)?*_set.begin():*_set.rbegin();
    }
};

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83824977