首页 > 其他 > 详细

[LeetCode] Majority Element II

时间:2015-06-30 12:17:59      阅读:128      评论:0      收藏:0      [点我收藏+]

Well, this problem becomes a little trickier since there may be more than one majority element. But, there can be at most two of them. This can be proved using proof by contradiction. If there are not less than 3 majority element and each appears more than n / 3 times, then nums will have 3 * n / 3 > n elements, which is a contradiction. Note that the floor sign does not affect the correctness of this proof. You may try some examples and convince yourself of this.

Now we maintain a vector<int> major for the majority elements. Once we meet an element which has appeared more than n / 3 times and have not been added to major, we add it tomajor. For counting the number of appearances, we use an unordered_map<int, int> counts. For telling whether it has been added, we use an unordered_set<int> exist to store the added elements.

Since we visit each element exactly once and the operations (search, insertion) w.r.t counts andexist (both are hash tables) is O(1), this idea can simply be proved to be of O(n) time-complexity.

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<int> majorityElement(vector<int>& nums) {
 4         vector<int> major; 
 5         unordered_map<int, int> counts;
 6         unordered_set<int> exist;
 7         int n = nums.size();
 8         for (int i = 0; i < n; i++) {
 9             counts[nums[i]]++;
10             if (counts[nums[i]] > n / 3 && exist.find(nums[i]) == exist.end()) {
11                 major.push_back(nums[i]);
12                 exist.insert(nums[i]);
13             }
14             if (major.size() == 2) break;
15         }
16         return major;
17     }
18 };

 

[LeetCode] Majority Element II

原文:http://www.cnblogs.com/jcliBlogger/p/4609998.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!