分治算法求众数c语言
时间: 2023-08-03 15:09:40 浏览: 47
以下是使用分治算法求众数的 C 语言实现:
```c
int majority_element(int* nums, int numsSize) {
if (numsSize == 1) {
return nums[0];
}
int mid = numsSize / 2;
int left_majority = majority_element(nums, mid);
int right_majority = majority_element(nums + mid, numsSize - mid);
if (left_majority == right_majority) {
return left_majority;
}
int left_majority_count = 0;
int right_majority_count = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] == left_majority) {
left_majority_count++;
} else if (nums[i] == right_majority) {
right_majority_count++;
}
}
return left_majority_count > right_majority_count ? left_majority : right_majority;
}
```
该算法的时间复杂度为 $O(n \log n)$,其中 $n$ 是数组的大小。
阅读全文