0
点赞
收藏
分享

微信扫一扫

剑指Offer 刷题 数组中出现次数超过一半的数字


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


剑指Offer  刷题   数组中出现次数超过一半的数字_i++


剑指Offer  刷题   数组中出现次数超过一半的数字_i++_02

public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int count = 0;
int res = 0;
int len = array.length;
for(int i = 0;i<len;i++){
//初始化 or 重复数字被抵消,重新选出大哥
if(count==0){
res = array[i];
}
//如果重复,计数器加1,否则计数器-1
count += res==array[i]?1:-1;
}
//验证:
count = 0;
for (int i = 0; i < len; i++) {
if (res == array[i]) {
count++;
}
}
return count>len/2?res:0;

}
}


举报

相关推荐

0 条评论