题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
简单的做法,hash表记录出现次数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public int MoreThanHalfNum_Solution(int [] array) { int len=array.length; Map<Integer,Integer> map=new HashMap<>(); for (int i : array) { if (!map.containsKey(i)) { map.put(i,1); }else { map.put(i,map.get(i)+1); } } for (Integer integer : map.keySet()) { if (map.get(integer)>len/2){ return integer; } } return 0; }
|
用tmp记录上一次访问的值,count表明当前值出现的次数,如果下一个值和当前值相同那么count++;如果不同count–,count减到0的时候就要更换新的tmp值了。如果存在超过数组长度一半的值tmp,那么最后一定会使count大于0。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| public int MoreThanHalfNum_Solution(int[] array) { if (array == null || array.length == 0) { return 0; } if (array.length == 1) { return array[0]; } int tmp = array[0], count = -1; for (int i = 1; i < array.length; i++) { if (count == -1) { count = 0; } if (array[i] == tmp) { count++; } else { count--; } if (count == 0) { tmp = array[i]; count = -1; } } return count <= 0 ? 0 : tmp; }
|