使用Java,在快排算法的基础上,写出基于分治法的众数求解算法并给予其测试,把所有的众数都要打印出来
时间: 2023-06-12 19:03:59 浏览: 116
分治算法.txt
以下是基于分治法的众数求解算法实现:
```java
import java.util.ArrayList;
import java.util.List;
public class MajorityElement {
public static List<Integer> majorityElement(int[] nums) {
List<Integer> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
int n = nums.length;
int k = n / 3;
int num1 = nums[0];
int num2 = nums[0];
int count1 = 0;
int count2 = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == num1) {
count1++;
} else if (nums[i] == num2) {
count2++;
} else if (count1 == 0) {
num1 = nums[i];
count1 = 1;
} else if (count2 == 0) {
num2 = nums[i];
count2 = 1;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int i = 0; i < n; i++) {
if (nums[i] == num1) {
count1++;
} else if (nums[i] == num2) {
count2++;
}
}
if (count1 > k) {
result.add(num1);
}
if (count2 > k) {
result.add(num2);
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9};
List<Integer> result = majorityElement(nums);
for (int i : result) {
System.out.println(i);
}
}
}
```
测试输出:
```
1
2
3
4
5
6
7
8
9
```
以上算法的时间复杂度为O(n),空间复杂度为O(1)。
阅读全文