剑指Offer第十九题:数组中出现次数超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
题目分析
这个题基于桶排序的思路改进的。
- 假如,我们使用一个数组array,将数组初始化,每个值都为0,然后我们开始遍历题目所给的数组,当遍历到1时,那么array[1]=array[1]+1;遍历到2时那么array[2]=array[2]+1.............遍历变成之后,我们只需要找到数组最大的数,输入该序号就可以了。Ps:该思想就是桶排序的思路 。
- 思路虽好,但是不适应,加入这个输入的数组特别大或者其中的一个数值特别大,那么这个空间复杂度就会很大。但是假如我们采用Key-Value的形式存储呢,是不是就很简单了。
源代码(HashMap实现)
1 public static int MoreThanHalfNum_Solution(int [] array) { 2 HashMap<Integer, Integer> map=new HashMap<>(); 3 4 int Max=array.length/2; 5 for(int i=0;i<array.length;i++) { 6 if(map.containsKey(array[i])) {//假如array的当前值,在map中的key值已经存在,那么我们直接修改这个key的value。 7 int num=map.get(array[i]);//获取value; 8 num=num+1; //增加value 9 map.remove(array[i]); //移除这个key-value 10 map.put(array[i], num); //再插入新的key-value键值对,因为HashMap没有提供修改值操作,所以只能这样 11 }else { 12 map.put(array[i], 1); 13 } 14 } 15 int value=0; 16 int y=0; 17 Iterator<Entry<Integer, Integer>> iterator=map.entrySet().iterator();//使用Iterator遍历出Entry对象 18 while(iterator.hasNext()) { 19 Map.Entry<Integer, Integer> entry=(Map.Entry<Integer, Integer>)iterator.next(); 20 21 if(value<entry.getValue()) { 22 value=entry.getValue(); 23 y=entry.getKey(); 24 } 25 } 26 if(Max<value) 27 return y; 28 return 0; 29 30 }
Ps:不明白其用法参考我的博客JAVA集合系列