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.
这道题我的方法是先将数组进行排序,然后从第一个数开始进行比较,往后记录每次相同的数的个数,如果遇到不同的就重置,直到遇到相同的数出现了⌊ n/2 ⌋ 次,代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
int Maxnum = nums[0];
int Maxcount = 0;
int curNum = nums[0];
for(int i = 0 ; i < nums.size(); i++){
if(nums[i] == curNum ){
Maxcount++;
if(Maxcount > nums.size()/2){
return nums[i];
}
}
else{
Maxcount = 1;
curNum = nums[i];
}
}
}
};