-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathSolution020.java
More file actions
38 lines (33 loc) · 845 Bytes
/
Solution020.java
File metadata and controls
38 lines (33 loc) · 845 Bytes
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
package algorithm.tmop;
/**
* @author: mayuan
* @desc: 出现次数超过一半的数
* 时间复杂度: O(n)
* 空间复杂度: O(1)
* @date:
*/
public class Solution020 {
public static void main(String[] args) {
int[] array = {3, 1, 2, 3, 3, 0, 3};
System.out.println(findNumber(array));
}
public static int findNumber(int[] array) {
if (null == array || 0 >= array.length) {
return -1;
}
int number = array[0];
int count = 1;
for (int i = 1; i < array.length; ++i) {
if (array[i] == number) {
++count;
} else {
if (1 == count) {
number = array[i];
} else {
--count;
}
}
}
return number;
}
}