[LeetCode]Majority Element

Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

最简单的方法就是排序,然后中间的那个数字就是我们需要的结果,两行搞定,时间复杂度就是排序的最优值O(nlogn)。

1 class Solution {
2 public:
3     int majorityElement(vector<int>& nums) {
4         sort(nums.begin(),nums.end());
5         return nums[nums.size()/2];
6     }
7 };

利用Hash Table可以实现O(n)的时间复杂度。

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         unordered_map<int,int> showed;
 5         for(int i=0;i<nums.size();i++)
 6         {
 7             if(showed.find(nums[i])==showed.end())
 8             {
 9                 showed[nums[i]]=1;
10             }
11             else
12             {
13                 showed[nums[i]]++;
14             }
15         }
16         unordered_map<int,int>::iterator iter;
17         for(iter=showed.begin();iter!=showed.end();iter++)
18         {
19             if(iter->second>nums.size()/2)
20             {
21                 return iter->first;
22             }
23         }
24     }
25 };

还有一种比较巧的方法,moore voting算法,时间复杂度也是O(n)。

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int result;
 5         int count=0;
 6         for(int i=0;i<nums.size();i++)
 7         {
 8             if(count==0)
 9             {
10                 result=nums[i];
11                 count=1;
12             }
13             else
14             {
15                 if(nums[i]==result) count++;
16                 else count--;
17             }
18         }
19         return result;
20     }
21 };

这是官网给的解法提示。

 

posted @ 2015-09-06 16:08  Sean_le  阅读(194)  评论(0编辑  收藏  举报