数组中出现次数超过一半的数字
来源:互联网 发布:阿里云 内网穿透 编辑:程序博客网 时间:2024/06/07 00:06
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
public class Solution { boolean isInvalid=false; public int MoreThanHalfNum_Solution(int [] array) { if(CheckInvalidArray(array,array.length)){ return -1; } int result=array[0]; int count=1; for(int i=1;i<array.length;i++){ if(count==0){ result=array[i]; count=1; }else if(array[i]==result){ count++; }else{ count--; } } if(!CheckMoreThanHalf(array,array.length,result)){ result=0; } return result; } //判断数组是否为null或者数组长度为0,我们在这里封装成一个函数,以后多考虑这种用法 private boolean CheckInvalidArray(int[] arr,int length){ isInvalid=false; //输入无效的情况 if(arr==null||length==0){ isInvalid=true; } return isInvalid; } //判断一个数字的出现次数是否超过数组元素的一半 private boolean CheckMoreThanHalf(int[] arr,int length,int number){ int count=0; for(int i=0;i<length;i++){ if(arr[i]==number){ count++; } } boolean isMoreThanHalf=true; if(count*2<=length){ isInvalid=true; isMoreThanHalf=false; } return isMoreThanHalf; }}
public class Solution { public int MoreThanHalfNum_Solution(int [] array) { if(array==null||array.length==0){ return -1; } //使用哈希表 int mapArr[]=new int[256]; for(int i=0;i<mapArr.length;i++){ mapArr[i]=0; } for(int i=0;i<array.length;i++){ mapArr[array[i]]++; } for(int i=0;i<mapArr.length;i++){ if(mapArr[i]>(array.length)/2){ return i; } } //没有找到这样的数字 return 0; }}
阅读全文
0 0
- 数组中超过出现次数超过一半的数字
- 74.数组中超过出现次数超过一半的数字
- 74 数组中超过出现次数超过一半的数字
- 【数组4】数组中出现次数超过一半的数字
- 数组4:数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过长度一半的数字
- 2-数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字[算法]
- 数组中出现次数超过一半的数字
- 找出数组中出现次数超过一半的数字--百度
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- 寻找数组中出现次数超过一半的数字
- 面试训练数组中出现次数超过一半的数字
- 数组中出现次数超过一半的数字
- HashMap底层详解-002-hash算法、长度的秘密
- 倒计时:11.16今晚8点CSDN直播《C语言大型软件设计的面向对象》
- HashMap底层详解-003-resize、并发下的安全问题
- ncaught Error: [$injector:cdep] angular 循环依赖
- 迷茫的程序员
- 数组中出现次数超过一半的数字
- 网易2017春招编程题:赶去公司 [python]
- 从paxos到zookeeper读书笔记(第四章)
- 代码生成工具 rapid-framework
- 对字典对象组成的List集合进行Lambda表达式的GroupBy
- mybatis java.sql.SQLException: 无效的列类型
- 剖析InnoDB与MyISAM的区别-mysql
- Java-001-认识Java
- 数据库和数据仓库的区别?