摩尔投票算法是一种高效的算法,用于在数组中寻找出现次数超过一半或特定比例的元素。以下是摩尔投票算法的Java实现及其详细解析。
javapublic class MajorityElement {
public static int findMajorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
count = 1;
} else if (candidate == num) {
count++;
} else {
count--;
}
}
// 验证候选元素是否确实超过半数
count = 0;
for (int num : nums) {
if (num == candidate) {
count++;
}
}
return count > nums.length / 2 ? candidate : -1; // 返回-1表示没有多数元素
}
public static void main(String[] args) {
int[] nums = {3, 2, 3, 3, 4, 3, 5, 3};
int majorityElement = findMajorityElement(nums);
System.out.println("出现次数超过一半的元素是:" + majorityElement);
}
}
candidate
和计数器count
为0count
为0时,将当前元素设为候选元素count
加1count
减1该算法时间复杂度为O(n),空间复杂度为O(1)
javaimport java.util.ArrayList;
import java.util.List;
public class MajorityElementII {
public static List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
int candidate1 = 0, candidate2 = 0;
int count1 = 0, count2 = 0;
// 第一轮遍历找出两个候选元素
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
} else if (count1 == 0) {
candidate1 = num;
count1 = 1;
} else if (count2 == 0) {
candidate2 = num;
count2 = 1;
} else {
count1--;
count2--;
}
}
// 第二轮遍历验证候选元素
count1 = 0;
count2 = 0;
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
}
}
if (count1 > nums.length / 3) {
result.add(candidate1);
}
if (count2 > nums.length / 3 && candidate1 != candidate2) {
result.add(candidate2);
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 3, 3, 2, 2, 2};
List<Integer> majorityElements = majorityElement(nums);
System.out.println("出现次数超过n/3的元素是:" + majorityElements);
}
}
candidate1
、candidate2
和对应的计数器count1
、count2
该算法同样保持O(n)时间复杂度和O(1)空间复杂度
摩尔投票算法因其简洁高效的特点,成为解决多数元素问题的首选方案。