[Array]414. Third Maximum Number

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.
思路:找出一个数组中第三大的元素,这里只是说integer,没有规定范围,因此应该考虑到int型的最大值和最小值,INT_MIN,INT_MAX,
自己的想法:(129ms)比较简单,使用额外的辅助空间,将不重复的元素排序
 1 int thirdMax(vector<int>& nums) {
 2         sort(nums.begin(),nums.end());
 3         vector<int> ans;
 4         int i;
 5         for(i=nums.size()-1;i>=0;--i)
 6         {
 7             if(find(ans.begin(),ans.end(),nums[i])==ans.end())//一开始自己的想法是进行排序,然后相邻元素是否相等,
 8                 ans.push_back(nums[i]);
 9         }
10         if(ans.size()<3)
11             return ans[0];
12         return ans[2];
13     }

或者这样:

 

优秀代码:(6ms)既然要找出第三大的元素值,则首先设定三个最小值,然后遍历所有的元素,找出前三大的元素值

 1 int thirdMax(vector<int>& nums) {
 2        long long  a, b, c;
 3         a = b = c = LONG_MIN  ;
 4         for(auto num : nums){
 5             if(num <= c || num ==b || num == a)
 6                 continue;
 7             else 
 8                 c = num;
 9             if(c > b)
10                 swap(b, c);
11             if(b > a)
12                 swap(a, b);
13         }
14         return c == LONG_MIN ? a : c;
15     }

函数set下的代码:

1 int thirdMax(vector<int>& nums) {
2         set<int> top;
3         for (auto i : nums) {
4             top.insert(i);
5             if (top.size() > 3) top.erase(top.begin());
6         }
7         return top.size() == 3 ? *top.begin() : *top.rbegin();
8     }

 set参考链接:http://www.cnblogs.com/BeyondAnyTime/archive/2012/08/13/2636375.html

posted @ 2017-08-13 20:41  两猿社  阅读(200)  评论(0编辑  收藏  举报