数组中出现次数超过一半的数字(牛客网十七)
2018-01-21 21:30
106 查看
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
public class Solution { public int MoreThanHalfNum_Solution(int [] array) { int len=array.length; int result=0; if(len==0) return result; int a=array[0]; int count=1; for(int i=1;i<len;i++) { if(a==array[i]) count++; else count--; if(count==0) { a=array[i]; count=1; } } if(checkmorethanhalf(a,array)) return a; else return 0; } boolean checkmorethanhalf(int a,int []array) { int len=array.length; int count=0; for(int i=0;i<len;i++) { if(a==array[i]) { count++; } } if(count>len/2) return true; else return false; } }
相关文章推荐
- 牛客网刷题|数组中出现次数超过一半的数字
- 牛客网刷题之数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 面试题29:数组中出现次数超过一半的数字
- 微信红包(数组中出现次数超过一半的数字)----腾讯2016研发工程师编程题
- 数据结构练习(35)数组中出现次数超过一半的数字
- 《剑指offer》数组中出现次数超过一半的数字
- 【剑指offer之数组中出现次数超过一半的数字 】
- 数组中出现次数超过一半的数字[算法]
- 【剑指offer】十九,数组中出现次数超过一半的数字
- 【算法习作】已知有一个数字在某数组中出现次数超过一半,求这个数
- 数组中出现次数超过一半的数字(剑指offer)
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 剑指offer 29. 数组中出现次数超过一半的数字
- 面试题29:数组中出现次数超过一半的数字
- 剑指offer——数组中出现次数超过一半的数字
- 【c语言】数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字
- 剑指offer面试题 求数组中出现次数超过一半的数字
- 数组中出现次数超过一半的一个数字