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.
这道题我采用从左到右相邻元素是否相同的比较去进行判断,不同则更新暂放的变量ele,最后留下的一定是主要元素,即每找出两个不同的element,就成对删除即count–。
代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int size=nums.size();
int ele=0;
int count=0;
for(int i=0;i<size;i++){
if(count==0)
{
ele=nums[i];
count=1;
}
else {
if(ele==nums[i]){
count++;
}
else{
count--;
}
}
}
return ele;
}
};