题目:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
作者是使用Java语言写的,但语法基本与C一致,读者可以直接查看方法(C称为函数)内部的代码,三种方法返回值都是int,形参都是整型数组
题解一:暴力求解
时间复杂度:O(n^2)
空间复杂度:O(n)
代码:
public static int halfMode(int[] arr){
int ret = arr[0];
int maxCount = 0;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if(arr[j] == arr[i]){
count++;
}
}
if(count > maxCount){
maxCount = count;
ret = arr[i];
}
}
return ret;
}
题解二:先排序再返回
时间复杂度:O(nlog(n))
空间复杂度:O(n)
代码:
public static int halfMode1(int[] arr){
//Java自带的快速排序函数
Arrays.sort(arr);
return arr[arr.length / 2];
}
题解三:投票法(只遍历一次,建议结合调试去理解)
时间复杂度:O(n)
空间复杂度:O(1)
原理:
代码:
public static int halfMode2(int[] arr){
int ret = arr[0];
int count = 1;
for (int i = 1; i < arr.length; i++) {
if(arr[ret] == arr[i]){
count++;
}else{
count--;
}
if(count == 0){
ret = arr[i + 1];
}
}
return ret;
}