0%

剑指offer039找出出现次数超过数组长度一半的数字

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 {
/*
第一种思路是比较正常的思路,用map记录所有数字出现的次数。然后直接进行比较就可以。
*/
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;
}

/*
某个数字出现的次数大于数组长度的一半,意思就是它出现的次数比其他所有数字出现的次数和还要多。因此我们可以在遍历数组的时候记录两个值:1. 数组中的数字;2. 次数。
遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。最后再判断它是否符合条件。
*/
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;
}

}