-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMoreThanHalfNum.java
36 lines (33 loc) · 1.05 KB
/
MoreThanHalfNum.java
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
package SwordToOffer;
import java.util.HashMap;
/**
* Created by tlh on 2017/3/17.
*/
public class MoreThanHalfNum {
public int MoreThanHalfNum_Solution(int[] array) {
if (array == null || array.length == 0)
throw new RuntimeException("Invalid Input.");
int result = array[0];
int count = 0;
HashMap<Integer, Integer> map = new HashMap<>(array.length);
for (int i = 0; i < array.length; i++) {
int num = array[i];
Integer cnt = map.get(num);
map.put(num, cnt != null ? cnt + 1 : 1);
if (count == 0) {
result = num;
count++;
} else if (result == num) {
count++;
} else {
count--;
}
}
if (map.get(result) > array.length / 2)
return result;
else return 0;
}
public static void main(String[] args) {
System.out.println(new MoreThanHalfNum().MoreThanHalfNum_Solution(new int[]{1, 2, 3, 2, 2, 2, 5, 4, 2}));
}
}