mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-31 02:53:42 +00:00
Update 39. 数组中出现次数超过一半的数字.md
补充题目描述;解题思路中补充摩尔投票算法抵消原理及示例说明,并调整第一遍遍历的代码实现。
This commit is contained in:
@@ -2,23 +2,30 @@
|
||||
|
||||
[Leetcode](https://leetcode.cn/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
数组中有一个数字出现的次数超过数组长度的一半,找出这个数字。
|
||||
|
||||
## 解题思路
|
||||
|
||||
多数投票问题,可以利用 Boyer-Moore Majority Vote Algorithm 来解决这个问题,使得时间复杂度为 O(N)。
|
||||
多数投票问题,可以利用多数投票算法(Boyer-Moore Majority Vote Algorithm)来解决这个问题,时间复杂度为 O(N),空间复杂度为 O(1)。
|
||||
|
||||
使用 cnt 来统计一个元素出现的次数,当遍历到的元素和统计元素相等时,令 cnt++,否则令 cnt--。如果前面查找了 i 个元素,且 cnt == 0,说明前 i 个元素没有 majority,或者有 majority,但是出现的次数少于 i / 2 ,因为如果多于 i / 2 的话 cnt 就一定不会为 0 。此时剩下的 n - i 个元素中,majority 的数目依然多于 (n - i) / 2,因此继续查找就能找出 majority。
|
||||
思路是让不同的数两两抵消。majority 记录候选值,cnt 记录它还没被抵消的次数:cnt 为 0 时把当前元素作为新的候选,之后遇到相同的数 cnt 加 1,不同的数 cnt 减 1。设出现次数超过一半的数为 x,每次抵消消耗两个不同的数,x 最多被其它数抵消的次数少于它自己的出现次数,因此最后留下的候选一定是 x。
|
||||
|
||||
例如 [3, 1, 3, 2, 3]:3 与 1 抵消,3 与 2 抵消,最后剩下的 3 就是答案。
|
||||
|
||||
第二次遍历统计候选的出现次数,用于题目不保证存在这样的数时(牛客的版本不存在时返回 0);力扣的版本保证存在,可以省略。
|
||||
|
||||
```java
|
||||
public int inventoryManagement(int[] stock) {
|
||||
int majority = stock[0];
|
||||
for (int i = 1, cnt = 1; i < stock.length; i++) {
|
||||
cnt = stock[i] == majority ? cnt + 1 : cnt - 1;
|
||||
if (cnt == 0) {
|
||||
majority = stock[i];
|
||||
cnt = 1;
|
||||
}
|
||||
}
|
||||
int cnt = 0;
|
||||
for (int val : stock) {
|
||||
if (cnt == 0)
|
||||
majority = val;
|
||||
cnt += val == majority ? 1 : -1;
|
||||
}
|
||||
cnt = 0;
|
||||
for (int val : stock) {
|
||||
if (val == majority) {
|
||||
cnt++;
|
||||
|
||||
Reference in New Issue
Block a user