用java实现分治法求众数算法
时间: 2024-03-28 12:12:27 浏览: 82
用分治实现的众数查找
5星 · 资源好评率100%
好的,以下是用Java实现分治法求众数算法的代码:
```java
public class MajorityElement {
public int majorityElement(int[] nums) {
return majorityElement(nums, 0, nums.length - 1);
}
private int majorityElement(int[] nums, int start, int end) {
if (start == end) {
return nums[start];
}
int mid = (end - start) / 2 + start;
int leftMajority = majorityElement(nums, start, mid);
int rightMajority = majorityElement(nums, mid + 1, end);
if (leftMajority == rightMajority) {
return leftMajority;
}
int leftCount = count(nums, leftMajority, start, end);
int rightCount = count(nums, rightMajority, start, end);
return leftCount > rightCount ? leftMajority : rightMajority;
}
private int count(int[] nums, int num, int start, int end) {
int count = 0;
for (int i = start; i <= end; i++) {
if (nums[i] == num) {
count++;
}
}
return count;
}
}
```
以上是分治法求众数算法的Java实现,希望可以帮助您解决问题。如果还有其他问题,请随时提出。
阅读全文