题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
思路:
一个数字,如果在数组中出现了超过1/2len的次数,那么遍历一遍就可以知道这个数字是什么。
我们只要做 比较 就可以了
从一开始,我们就做比较,如果相同的话,count ++ 如果不同的话 count--,当count减到0的时候,就将number更换成当前的数字。
这样是否可以呢?简单思考一下,如果目标数字 刚和其他数字抵消的话,那么最后数字就是 len (目标数字数目) -(len(all) - len( all -目标数字数目)),如果其他数字相互抵消的话,这样更好,这样最后剩下的count 更多,抵消一对的话+2;
如下图:第一个图中,每一个2刚和其他的数字抵消,这样正好留一下一个,而第二个图中,一开始1和3抵消了,这样比第一个图多留了2个
解答:
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int number =0;
int count =0;
for(int i=0;i<array.length;i++){
if(count ==0){
number = array[i];
count++;
continue;
}else {
if(array[i] == number){
count++;
}else {
count--;
if(count ==0)
number=0;
}
}
}
if(number ==0)
return 0;
else {
int len =0;
for(int i=0;i<array.length;i++)
if(number == array[i])
len++;
if(len >array.length/2)
return number;
else
return 0;
}
}
}