169. Majority Element
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.
注意此题中要求的数一定要超过半数
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count =0;
int num = 0;
for(auto n:nums){
if(n == num)
count++;
else if(count == 0)
num = n;
else
count--;
}
return num;
}
};
int majorityElement(vector<int>& nums) {
int count =0;
int num = 0;
for(auto n:nums){
if(count == 0){
num = n;
count = 1;
}else if(n == num)
count++;
else
count--;
}
return num;
}