Skip to content

Commit 6a9aee4

Browse files
committed
229
1 parent a323e75 commit 6a9aee4

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

leetcode-229-Majority-ElementII.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,60 @@ public List<Integer> majorityElement(int[] nums) {
110110

111111
当然,不用上边的技巧也是可以的,我们可以先在 `nums` 里找到两个不同的值分别赋值给 `group1``group2` 中即可,只不过代码上不会有上边的简洁。
112112

113+
`2020.5.27` 更新,[@Frankie](http://yaoyichen.cn/algorithm/2020/05/27/leetcode-229.html) 提醒,其实不用上边分析的那么麻烦,只需要给 `group1``group2` 随便赋两个不相等的值即可。
114+
115+
因为如果数组中前两个数有和 `group1` 或者 `group2` 相等的元素,就进入前两个 `if` 语句中的某一个,逻辑上也没问题。
116+
117+
如果数组中前两个数没有和 `group1` 或者 `group2` 相等的元素,那么就和使用 `long` 一个性质了。
118+
119+
```java
120+
public List<Integer> majorityElement(int[] nums) {
121+
int n = nums.length;
122+
int group1 = 0;
123+
int count1 = 0;
124+
int group2 = 1;
125+
int count2 = 0;
126+
for (int i = 0; i < n; i++) {
127+
if (nums[i] == group1) {
128+
count1++;
129+
} else if (nums[i] == group2) {
130+
count2++;
131+
} else if (count1 == 0) {
132+
group1 = nums[i];
133+
count1 = 1;
134+
} else if (count2 == 0) {
135+
group2 = nums[i];
136+
count2 = 1;
137+
} else {
138+
count1--;
139+
count2--;
140+
}
141+
}
142+
143+
//计算两个队伍的数量,因为可能只存在一个数字的数量超过了 n/3
144+
count1 = 0;
145+
count2 = 0;
146+
for (int i = 0; i < n; i++) {
147+
if (nums[i] == group1) {
148+
count1++;
149+
}
150+
if (nums[i] == group2) {
151+
count2++;
152+
}
153+
}
154+
//只保存数量大于 n/3 的队伍
155+
List<Integer> res = new ArrayList<>();
156+
if (count1 > n / 3) {
157+
res.add( group1);
158+
}
159+
160+
if (count2 > n / 3) {
161+
res.add(group2);
162+
}
163+
return res;
164+
}
165+
```
166+
113167
#
114168

115169
解法一算是通用的解法,解法二的话看起来比较容易,但如果只看上边的解析,然后自己写代码的话还是会遇到很多问题的,其中 `if` 分支的顺序很重要。

0 commit comments

Comments
 (0)