169.多数元素
大约 2 分钟
题目描述
给定一个大小为 n 的数组,返回其中的多数元素。多数元素是指在数组中出现次数严格大于 n/2 的元素。
你可以假设数组是非空的,并且数组总是存在多数元素。
示例 1:
输入: nums = [3,2,3]
输出: 3示例 2:
输入: nums = [2,2,1,1,1,2,2]
输出: 2解题思路:Boyer–Moore 投票算法
把数组扫描视为一个“对消”过程:选择一个候选 candidate 与计数 votes。遇到与候选相同的元素就增加票数,遇到不同的元素就减少票数;当票数为 0 时更换候选为当前元素。若存在多数元素,它在对消后会成为最后的候选。
算法步骤
- 初始化
candidate任意、votes = 0。 - 遍历数组:
- 若
votes == 0,设置candidate = num。 - 若
num == candidate,votes++;否则votes--。
- 若
- 遍历结束返回
candidate。
代码实现
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 读取数组长度
int n = scanner.nextInt();
int[] nums = new int[n];
// 读取数组元素
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
Solution solution = new Solution();
int result = solution.majorityElement(nums);
System.out.println(result);
scanner.close();
}
}
class Solution {
public int majorityElement(int[] nums) {
int candidate = 0, votes = 0;
for (int num : nums) {
if (votes == 0) candidate = num;
votes += (num == candidate) ? 1 : -1;
}
return candidate;
}
}变体说明
若题目不保证一定存在多数元素,可在得到 candidate 后进行一次统计验证:
class Solution {
public int majorityElement(int[] nums) {
int candidate = 0, votes = 0;
for (int num : nums) {
if (votes == 0) candidate = num;
votes += (num == candidate) ? 1 : -1;
}
int count = 0;
for (int num : nums) if (num == candidate) count++;
return count > nums.length / 2 ? candidate : -1; // 无多数时返回占位值
}
}复杂度分析
时间复杂度:O(n)
- 单次线性扫描,若含校验则为两次线性扫描,仍为 O(n)。
空间复杂度:O(1)
- 仅使用常数个额外变量。
对消保留“赢家”,票数清零换候选,最终留下的就是多数元素。
摩尔投票 其实就是对某个值进行投票 抵消,众数最后肯定还能剩一个
