剑指Offer(Java版)第三十三题:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

/*
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
*/

import java.util.*;

public class Class33 {

public int MoreThanHalfNum_Solution(int [] array) {
int length = array.length;
int count = 1;
int index = 0;
if(array == null || length <= 0){
return 0;
}
for(int i = 1; i < length; i++){
if(array[index] == array[i]){
count++;
}else if(array[index] != array[i]){
if(count == 0){
index = i;
count = 1;
}else{
count--;
}
}
}
count = 0;
for(int i = 0; i < length; i++){
if(array[i] == array[index]){
count++;
}
}
if(count > (length/2)){
return array[index];
}else{
return 0;
}

}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

posted on 2020-03-17 21:08  桌子哥  阅读(520)  评论(0编辑  收藏  举报