牛客网 | 数组中出现次数超过一半的数字
来源:互联网 发布:提高数据分析能力 编辑:程序博客网 时间:2024/04/30 18:09
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
本题O(n)的思想是,定义两个变量temp和count,每次循环时,如果array[i]的值等于temp,则count自增一,如不等并且count>0,则count自减一,若array[i]的值不等于temp并且count不大于0,重新对temp赋值为当前array[i],count赋值为1。
如存在大于一半的数,直接返回temp就是了,但测试数据中有不存在的情况,所以最后又来了一遍校验,检查当前temp值是否出现过一半以上。
public int MoreThanHalfNum_Solution(int [] array) { if (array.length==0) return 0; int num = array[0]; int count = 0; for (int i = 0; i < array.length; i++) { if(array[i]==num) count++; else count--; if(count==0) { num = array[i]; count=1; } } count = 0; for (int i = 0; i < array.length; i++) { if(array[i]==num) count++; } if(count*2>array.length) return num; return 0; }
0 0
- 牛客网 | 数组中出现次数超过一半的数字
- 数组中超过出现次数超过一半的数字
- 74.数组中超过出现次数超过一半的数字
- 74 数组中超过出现次数超过一半的数字
- 【数组4】数组中出现次数超过一半的数字
- 数组4:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过长度一半的数字
- 2-数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字[算法]
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过一半的数字--百度
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 寻找数组中出现次数超过一半的数字
- 面试训练数组中出现次数超过一半的数字
- NavigationItem的Title不居中,BackButton修改它得title
- 打字母游戏3
- 如何不停止服务清空nohup.out文件
- php常用代码大全
- iOS 分享(使用友盟sdk)
- 牛客网 | 数组中出现次数超过一半的数字
- POJ 2487 Stamps
- leetcode 235 Lowest Common Ancestor oa a Binary Search Tree
- FRM-40831错误的解决办法?
- scrollView中设置ImageView大小
- android资源目录---assets与res/raw区别
- Swift学习 下标脚本subscript和类扩展Extension
- 小随记
- Your project contains error(s),please fix them before running your application