題目描述
數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度爲9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。
解析思路
實現代碼
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int length = array.length;
if(array == null || length == 0){
return 0;
}
int tmp = array[0];
int counts= 1;
for(int i = 1;i<length;i++){
if(counts == 0){
tmp = array[i];
counts =1;
}else{
if(array[i] == tmp){
counts++;
}else{
counts--;
}
}
}
counts=0;
for(int i = 0;i<length;i++){
if(tmp == array[i]){
counts++;
}
}
if(counts*2>length){
return tmp;
}
return 0;
}
}