414. Third Maximum Number

方法一:利用set

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int thirdMax(vector<int>& nums) 
12     {
13         set<int> top3;
14         for(int i:nums)
15         {
16             top3.insert(i);
17             if(top3.size()>3)
18                 top3.erase(top3.begin());
19         }
20         return top3.size()==3?  *top3.begin():*top3.rbegin();
21     }
22 };

方法二:扫描数组,但是这里特殊情况很多,要注意通过标志位什么的予以解决

 1 static int wing=[]()
 2 {
 3     std::ios::sync_with_stdio(false);
 4     cin.tie(NULL);
 5     return 0;
 6 }();
 7 
 8 class Solution 
 9 {
10 public:
11     int thirdMax(vector<int>& nums) 
12     {
13         int rmin=INT_MIN,rmid=INT_MIN,rmax=INT_MIN;
14         int flag=0;
15         for(int i:nums)
16         {
17             if(i==rmin||i==rmid||i==rmax)
18             {
19                 if(i==rmin)
20                     flag=1;
21                 continue;
22             }
23             if(i>rmax)
24             {
25                 rmin=rmid;
26                 rmid=rmax;
27                 rmax=i;
28             }
29             else if(i>rmid)
30             {
31                 rmin=rmid;
32                 rmid=i;
33             }
34             else if(i>rmin)
35             {
36                 rmin=i;
37             }
38         }
39         if(rmin!=INT_MIN||(rmin!=rmid&&flag==1))
40             return rmin;
41         else
42             return rmax;
43     }
44 };

尤其是在原数组中含有INT_MIN时,很容易出问题,要注意排除。

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/9095537.html