LeetCode 229. Majority Element II

题目链接 Majority Element

题目链接 Majority Element II

这个题目非常有意思,算是我比较喜欢的类型,LeetCode中有些Medium还是是需要一些奇技淫巧的,比如这两道题.这两道题是一个叫Boyer-Moore的算法.

关于这个算法有两篇讲解我觉得特别好

LeetCode的ifyouseewendy大神

知乎的facetothefate大神

废话不多说,上代码,beat 几乎都是100%

Majority Element II

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
public static List<Integer> majorityElement(int[] nums) {
if (nums.length == 0) {
return new ArrayList<>();
} else if (nums.length == 1) {
return Arrays.asList(nums[0]);
}

int start1 = nums[0];
int cnt1 = 0;
int start2 = nums[0];
int cnt2 = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == start1) {
cnt1++;
} else if (nums[i] == start2) {
cnt2++;
} else if (cnt1 == 0) {
cnt1 = 1;
start1 = nums[i];
} else if (cnt2 == 0) {
cnt2 = 1;
start2 = nums[i];
} else {
cnt1--;
cnt2--;
}
}
if (cnt1 == 0 && cnt2 == 0) {
return new ArrayList<>();
} else {
List<Integer> result = new ArrayList<>();
int a = 0;
int b = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == start1) {
a++;
} else if (nums[i] == start2) {
b++;
}
}
if (a > nums.length / 3) {
result.add(start1);
}
if (b > nums.length / 3) {
result.add(start2);
}
return result;
}

}


Majority Element

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int majorityElement(int[] nums) {
int major = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
count++;
major = nums[i];
continue;
}
if (major == nums[i]) {
count++;
continue;
} else {
count--;
continue;
}

}
return major;
}


月月说要给我打赏,就还是放了二维码,😝