标签:
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 };
标签:
原文地址:http://www.cnblogs.com/hujian1994/p/5146735.html