-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMajorityElement.java
More file actions
53 lines (48 loc) · 1.27 KB
/
MajorityElement.java
File metadata and controls
53 lines (48 loc) · 1.27 KB
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
package com.algorithm.greedyalgorithm;
public class MajorityElement {
/**
* #169
* https://leetcode-cn.com/problems/majority-element
*
* @param args
*/
public static void main(String[] args) {
System.out.println(majorityElementII(new int[] { 1, 3, 1, 3, 1, 3, 2, 3, 1, 3}));
}
public static int majorityElement(int[] nums) {
int res = 0, cnt = 0;
for (int num : nums) {
if (cnt == 0) {
res = num;
cnt++;
} else {
if (res == num) {
cnt++;
} else {
cnt--;
}
}
}
return res;
}
public static int majorityElementII(int[] nums) {
int res = 0, n = nums.length;
for (int i = 0; i < 32; i++) {
int ones = 0, zeros = 0;
for (int num : nums) {
if (ones > n / 2 || zeros > n / 2) {
break;
}
if ((num & (1 << i)) != 0) {
++ones;
} else {
++zeros;
}
}
if (ones > zeros) {
res |= (1 << i);
}
}
return res;
}
}