码迷,mamicode.com
首页 > 其他好文 > 详细

169. Majority Element

时间:2016-01-20 22:28:16      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

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.

哈希实现

通过map计数即可

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) 
 4     {
 5         map<int, int> cnt;
 6         for(int i=0; i < nums.size(); i++)
 7             cnt[ nums[i] ]++;
 8 
 9         int n = nums.size();
10         for(map<int, int>::iterator iter = cnt.begin(); iter != cnt.end(); iter++)
11             if( iter->second > n/2 )
12                 return iter->first;
13     }
14 };

优化实现

每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的

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

 

169. Majority Element

标签:

原文地址:http://www.cnblogs.com/hujian1994/p/5146735.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!