From 6a84964eb842de5886d4bcb0983ca83fadbc4d20 Mon Sep 17 00:00:00 2001 From: CyC2018 Date: Fri, 30 Oct 2026 20:18:03 +0800 Subject: [PATCH] =?UTF-8?q?Update=2039.=20=E6=95=B0=E7=BB=84=E4=B8=AD?= =?UTF-8?q?=E5=87=BA=E7=8E=B0=E6=AC=A1=E6=95=B0=E8=B6=85=E8=BF=87=E4=B8=80?= =?UTF-8?q?=E5=8D=8A=E7=9A=84=E6=95=B0=E5=AD=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充题目描述;解题思路中补充摩尔投票算法抵消原理及示例说明,并调整第一遍遍历的代码实现。 --- notes/39. 数组中出现次数超过一半的数字.md | 25 +++++++++++++++-------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/notes/39. 数组中出现次数超过一半的数字.md b/notes/39. 数组中出现次数超过一半的数字.md index 1096b30f..4c6b6d05 100644 --- a/notes/39. 数组中出现次数超过一半的数字.md +++ b/notes/39. 数组中出现次数超过一半的数字.md @@ -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++;