面試題39:陣列中出現次數超過一半的數字
陣列中有一個數字出現的次數超過陣列長度的一半,找出這個數字,
// 摩爾投票法
class Solution {
public:
int majorityElement(vector<int>& nums) {
int x,votes;
for(int num:nums)
{
if(votes==0)
x = num;
votes += num==x? 1:-1; // votes += (num==x? 1:-1)
}
return x;
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/357040.html
標籤:其他
