LeetCode 169. Majority Element
2017-08-30 12:57
405 查看
问题:
Given an array of size n, find the majority element. The majority element is the element that appears more than
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
问题描述:
找出当前数组中出现的次数最多的,其中最多的那个数出现的次数一定超过[n/2].
问题分析:
这个这个问题如果用一般的方法做就是先用一个Map统计出每个数值出现的次数,然后找出最大的那一个。
但是这个问题中添加了一个额外的条件是 出现最多的数出现的次数超过了[n/2].
这样就有一种额外的解法:
找出两个不同的数都减一,知道最后剩下的哪个数。由于出现最多的数出现的次数超过了[n/2].那么无论如何排列进行减,最终留下的一定是出现最多的哪个数。
代码实现:
if (nums == null || nums.length == 0) {
return 0;
}
int maxCount = 0;
int num = -1;
for (int i = 0; i < nums.length; i++) {
if (maxCount == 0) {
num = nums[i];
maxCount = 1;
} else if (num != nums[i]) {
maxCount--;
} else {
maxCount++;
}
}
return num;
正常解法是先统计,然后进行找出出现次数最多的解法 。这里用了一种做减法的思路,同时由于有了>[n/2]这个条件使得这种实现变得正常。
Given an array of size n, find the majority element. The majority element is the element that appears more than
⌊ n/2 ⌋times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
问题描述:
找出当前数组中出现的次数最多的,其中最多的那个数出现的次数一定超过[n/2].
问题分析:
这个这个问题如果用一般的方法做就是先用一个Map统计出每个数值出现的次数,然后找出最大的那一个。
但是这个问题中添加了一个额外的条件是 出现最多的数出现的次数超过了[n/2].
这样就有一种额外的解法:
找出两个不同的数都减一,知道最后剩下的哪个数。由于出现最多的数出现的次数超过了[n/2].那么无论如何排列进行减,最终留下的一定是出现最多的哪个数。
代码实现:
if (nums == null || nums.length == 0) {
return 0;
}
int maxCount = 0;
int num = -1;
for (int i = 0; i < nums.length; i++) {
if (maxCount == 0) {
num = nums[i];
maxCount = 1;
} else if (num != nums[i]) {
maxCount--;
} else {
maxCount++;
}
}
return num;
正常解法是先统计,然后进行找出出现次数最多的解法 。这里用了一种做减法的思路,同时由于有了>[n/2]这个条件使得这种实现变得正常。
相关文章推荐
- LeetCode 169. Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- leetcode169. Majority Element
- LeetCode66/169/79 Plus One/Majority Element /Word Search
- Leetcode 169. Majority Element (Easy) (cpp)
- LeetCode(169) Majority Element (Java)
- LeetCode 169. Majority Element and LeetCode 229. Majority Element II解题报告
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- LeetCode 169. Majority Element
- [leetcode] 169. Majority Element
- 【LeetCode】169_Majority Element
- LeetCode 169 --- Majority Element
- 【leetcode】169. Majority Element
- Leetcode 169. Majority Element
- 2018.03.07 leetcode 打卡 #169. Majority Element
- 【LEETCODE】169-Majority Element
- Leetcode 169, 229 Majority element
- Leetcode ☞ 169. Majority Element
- LeetCode 169. Majority Element