原题:
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.
解:int majorityElement(vector<int>& nums) {
int vote=0,result,len=nums.size();
for(int i=0; i<len;i++){
if(vote==0){
result = nums[i];
vote = 1;
}
else{
if(result==nums[i])
vote++;
else
vote--;
}
}
return result;
}
原本想找一题分治的题目做,然而看完题目感觉是一个o(n)的题啊,上网搜了一下,发现全是用moore voting来解的,解法是o(n)
解题思路:
由于n(majority element)>n/2,所以遇到majority element则加一,否则则减一,最后结果肯定是大于0的。实际并不是说预先就知道哪个是majority element,但大概原理是这样