题目地址:
https://leetcode.com/problems/majority-element/
给定一个长度 n n n的数组 A A A,题目保证存在一个数出现次数超过一半。问这个数是多少。
用Moore投票算法,思路参考https://blog.csdn.net/qq_46105170/article/details/105378355。代码如下:
public class Solution {
public int majorityElement(int[] nums) {
int n = nums[0], count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == n) {
count++;
} else {
if (count == 0) {
n = nums[i];
count = 1;
} else {
count--;
}
}
}
return n;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。