CS-Notes/notes/39. 数组中出现次数超过一半的数字.md
2019-11-02 17:33:10 +08:00

35 lines
1.4 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 39. 数组中出现次数超过一半的数字
[NowCoder](https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 解题思路
多数投票问题可以利用 Boyer-Moore Majority Vote Algorithm 来解决这个问题使得时间复杂度为 O(N)
使用 cnt 来统计一个元素出现的次数当遍历到的元素和统计元素相等时 cnt++否则令 cnt--如果前面查找了 i 个元素 cnt == 0说明前 i 个元素没有 majority或者有 majority但是出现的次数少于 i / 2 因为如果多于 i / 2 的话 cnt 就一定不会为 0 此时剩下的 n - i 个元素中majority 的数目依然多于 (n - i) / 2因此继续查找就能找出 majority
```java
public int MoreThanHalfNum_Solution(int[] nums) {
int majority = nums[0];
for (int i = 1, cnt = 1; i < nums.length; i++) {
cnt = nums[i] == majority ? cnt + 1 : cnt - 1;
if (cnt == 0) {
majority = nums[i];
cnt = 1;
}
}
int cnt = 0;
for (int val : nums)
if (val == majority)
cnt++;
return cnt > nums.length / 2 ? majority : 0;
}
```
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>