数组中出现超过一半的数字

题目

https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof

解法

摩尔投票

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int majorityElement(int[] nums) {
int x=0, votes = 0;
for (int num : nums) {
if (votes == 0) x = num;

votes += num==x ? 1:-1;
}
int count =0;
for (int num : nums) {
if (num ==x) {
count++;
}
}
return count > nums.length/2 ? x : 0;
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×