Problem:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| public class CodingInterview_039 {
public int MoreThanHalfNumWithMap_Solution(int [] array) { int num = 0;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); int len = array.length ; if(len == 0) return 0; for(int i = 0; i < len ;i++){ if(map.containsKey(array[i])){ int count = map.get(array[i]); ++count; map.put(array[i],count); }else{ map.put(array[i],1); } } for(Map.Entry<Integer,Integer> entry: map.entrySet()){ if(entry.getValue() > (len/2)){ num = entry.getKey(); }
} return num; }
public int MoreThanHalfNum_Solution(int [] array) { int res = array[0], count = 1; for(int i=1; i<array.length; i++){ if(array[i] == res) count++; else{ count--; } if(count == 0){ res = array[i]; count = 1; } } count = 0; for(int i=0; i<array.length; i++){ if(array[i] == res) count++; } return count > array.length/2 ? res : 0; }
}
|