摩尔投票法(Moore Voting Algorithm)是一种用于找出在数组中出现次数超过一半的元素的算法。
public class MajorityElement {
public static int findMajorityElement(int[] nums) {
int count = 0;
int majorityElement = 0;
for (int num : nums) {
if (count == 0) {
majorityElement = num;
count++;
} else if (majorityElement == num) {
count++;
} else {
count--;
}
}
return majorityElement;
}
public static void main(String[] args) {
int[] nums = {3, 2, 3, 3, 4, 3, 5, 3};
int majorityElement = findMajorityElement(nums);
System.out.println("出现次数超过一半的元素是:" + majorityElement);
}
}
在上述代码中,我们使用了一个变量 count
来记录当前遍历到的元素的累计次数,以及一个变量 majorityElement
来保存当前的候选主要元素。
算法的核心思想是通过不断抵消数组中不同的元素,最终剩下的元素就是出现次数超过一半的元素。具体的执行过程如下:
- 初始化
count
和majorityElement
为 0。 - 遍历数组中的每个元素:
- 如果
count
为 0,将当前元素设置为majorityElement
,并将count
加 1。 - 否则,如果当前元素和
majorityElement
相等,将count
加 1。 - 否则,将
count
减 1。
- 如果
- 返回
majorityElement
。
在示例代码中,我们使用数组 [3, 2, 3, 3, 4, 3, 5, 3]
进行测试,其中元素 3
出现的次数超过一半。运行代码后,将输出结果为 "出现次数超过一半的元素是:3"。