常规算法不就说了,这次看到大佬的题解,特地记录以下。
解法名称为:摩尔投票法
假设出现次数最多的数字为 x,当nums[i] == x 时,votes += 1,否则 votes -= 1
由此我们可以知道,遍历完数组后,votes > 0
因此若数组中前m个数的和为0,那么后(n-m)个数的和仍大于0,出现次数最多的数字仍为 x
class Solution {
public:
int majorityElement(vector<int>& nums) {
int x = 0,votes = 0;
for(int i = 0; i< nums.size(); i++){
if(votes == 0){
x = nums[i];
}
votes += nums[i] == x ? 1 : -1;
}
return x;
}
};