169. 多数元素
掌握程度:★★
思路:遇到不相等的count-1,最后留下来的num就是众数
class Solution {
public int majorityElement(int[] nums) {
int num = nums[0];
int count = 1;
for(int i = 1; i < nums.length; i++){
if(nums[i] == num){
count++;
}else if(nums[i] != num){
count--;
if(count == 0){
count = 1;
num = nums[i];
}
}
}
return num;
}
}
229. 多数元素 II
掌握程度:★
class Solution {
// 思路:最多只有两位候选人的原因,如果有3位大于n/3,则总数超过n了
public List<Integer> majorityElement(int[] nums) {
// 创建返回值
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;
// 初始化两个候选人candidate,和他们的计票
int cand1 = nums[0], count1 = 0;
int cand2 = nums[0], count2 = 0;
// 摩尔投票法,分为两个阶段:配对阶段和计数阶段
// 配对阶段
for (int num : nums) {
// 投票
if (cand1 == num) {
count1++;
continue;
}
if (cand2 == num) {
count2++;
continue;
}
// 第1个候选人配对
if (count1 == 0) {
cand1 = num;
count1++;
continue;
}
// 第2个候选人配对
if (count2 == 0) {
cand2 = num;
count2++;
continue;
}
count1--;
count2--;
}
// 计数阶段
// 找到了两个候选人之后,需要确定票数是否满足大于 N/3
count1 = 0;
count2 = 0;
for (int num : nums) {
if (cand1 == num) count1++;
else if (cand2 == num) count2++;
}
if (count1 > nums.length / 3) res.add(cand1);
if (count2 > nums.length / 3) res.add(cand2);
return res;
}
}