🌗 剑指 Offer 39. 数组中出现次数超过一半的数字
2022年10月10日
- algorithm
🌗 剑指 Offer 39. 数组中出现次数超过一半的数字
难度: 🌗
问题描述
解法
class Solution {
public int majorityElement(int[] nums) {
// 思路:
// 摩尔投票
int res = nums[0];
int count = 1;
int len = nums.length;
for(int i = 1; i < len; i ++) {
if(res == nums[i]) {
count ++;
} else {
count --;
if(count == 0) {
res = nums[i];
count = 1;
}
}
}
return res;
}
}