import java.util.*;
public class MoreThanHalfNum_Solution {
//算法一:暴力搜索,复杂度O(n^2)
public int moreThanHalfNum_Solution(int [] array) {
if(array == null || array.length <= 0) return 0;
if(array.length == 1) return array[0];
boolean flag = false;
int result = 0;
List<Integer> list = new ArrayList<Integer>();
for(int i = 0;i < array.length - 1;i ++) {
if(!list.contains(array[i])) {
int count = 1;
list.add(array[i]);
for(int j = i + 1;j < array.length;j ++) {
if(array[j] == array[i]) count ++;
if(count > array.length / 2) {
flag = true;
result = array[j];
break;
}
}
}
if(flag == true) break;
}
return result;
}
//算法二复杂度:O(n)
public int moreThanHalfNum_Solution2(int [] array) {
if(array.length == 1) return array[0];
int count = 1;
int result = array[0];
for(int i = 1;i < array.length;i ++) {
if(array[i] == result) {
count ++; //出现跟自己相同的数,计数器就加一
}
else {
count --; //出现跟自己不同的数,计数器就减一
if(count == 0) { //减到0了就重新赋值result并重新计数
result = array[i];
count = 1;
}
}
}
//验证result是否出现次数超过一半
count = 0;
for(int i = 0;i < array.length;i ++) {
if(array[i] == result) {
count ++;
}
}
if(count <= array.length / 2) {
result = 0;
}
return result;
}
//算法三复杂度:Arrays.sort()使用了归并排序,时间复杂度为O(nlogn)
public int MoreThanHalfNum_Solution3(int [] array) {
if(array == null || array.length <= 0) return 0;
if(array.length == 1) return array[0];
Arrays.sort(array);
int result = array[array.length / 2]; //排序之后出现次数超过一半的数必是中位数
//验证中位数是否出现次数超过一半
int count = 0;
for(int i = 0;i < array.length;i ++) {
if(array[i] == result) {
count ++;
}
}
if(count <= array.length / 2) {
result = 0;
}
return result;
}
public static void main(String[] args) {
int [] array = {1,2,3,2,2,2,5,4,2};
System.out.println(new MoreThanHalfNum_Solution().moreThanHalfNum_Solution2(array));
}
}
《剑指offer》-找出数组中出现次数超过一半的数字
最新推荐文章于 2020-09-25 23:16:30 发布