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.
题意:
给定size 为n的数组,查找出主元素,就是出现次数大于n/2次的元素。你可以假定数组非空,而且主元素一定存在。
class Solution {
public:
int majorityElement(vector<int>& nums) {
int result = 0;
int count = 0;
for(int i=0;i<nums.size();i++){
if(count == 0){
result = nums[i];
count++;
}else{
if(result == nums[i]){
count++;
}else{
count--;
}
}
}
return result;
}
};