LeetCode#169. Majority Element(超過陣列長度一半的元素)
阿新 • • 發佈:2019-01-30
- 題目:給定一個數組,並且陣列中存在一個元素,該元素在陣列中的出現次數超過陣列長度的一半(n/2)
- 難度:Easy
- 思路:A Fast Ma jority Vote Algorithm 陣列中相鄰的兩個元素,如果元素值不同,則可以相互抵消。經過抵消後,剩餘元素一定是那個要尋找的元素。另一種思路可參考https://bestswifter.com/arrayoccurmorethanhalf/
- 程式碼:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 1 ;
int max = nums[0];
for(int i = 1; i < nums.size(); i++){
if(count == 0){
count++;
max = nums[i];
}else if (max == nums[i]){
count++;
}else{
count--;
}
}
return max;
}
};