給定一個大小爲 n 的數組,找到其中的多數元素。多數元素是指在數組中出現次數大於 ⌊ n/2 ⌋ 的元素。
你可以假設數組是非空的,並且給定的數組總是存在多數元素。
示例 1:
輸入: [3,2,3]
輸出: 3
示例 2:
輸入: [2,2,1,1,1,2,2]
輸出: 2
這裏,首先了解到,多數元素是指數組中大於size一半的元素,設置第一個數爲target,並令count=1;然後,與後面元素作比較,相等時,count加1 ,不等時,count減一,當count爲0時,此時的元素設爲target。
衆數一定比其他總數還要多,因此無論如何抵消,其個數一定大於等於1.
int majorityElement(vector<int>& nums) {
if(nums.size()<2)
return nums[0];
int count=1;
int target=nums[0];
for(int j=1;j<nums.size();j++){
if(nums[j]!=target){
count--;
if(count==0){
target=nums[j];
count=1;
}
}
else{
count++;
}
}
return target;
}