刷题遇到要求时间复杂度 O(n) 和空间复杂度 O(1)的算法题(求主元素),看到题解中的投票算法很不错,就记录了下来!
在每一轮投票过程中,从数组中删除两个不同的元素,直到投票过程无法继续,此时数组为空或者数组中剩下的元素都相等。
由于不一定存在主要元素,因此需要第二次遍历数组,验证 candidate 是否为主要元素。第二次遍历时,统计 candidate 在数组中的出现次数,如果出现次数大于数组长度的一半,则 candidate 是主要元素,返回 candidate,否则数组中不存在主要元素,返回 −1。
为什么当数组中存在主要元素时,Boyer-Moore 投票算法可以确保得到主要元素?
在 Boyer-Moore 投票算法中,遇到相同的数则将 count 加 1,遇到不同的数则将 count 减 1。根据主要元素的定义,主要元素的出现次数大于其他元素的出现次数之和,因此在遍历过程中,主要元素和其他元素两两抵消,最后一定剩下至少一个主要元素,此时 candidate 为主要元素,且 count≥1。
给定一个整型数组,找出主元素,它在数组中的出现次数大于数组元素个数的二分之一。要求时间复杂度为O(n),空间复杂度为O(1)。
python3
from typing import (
List,
)
class Solution:
"""
@param nums: a list of integers
@return: find a majority number
"""
def majority_number(self, nums: List[int]) -> int:
# write your code here
n = len(nums)
x, cnt = -1, 0
for i in nums:
if not cnt:
x = i
if x == i:
cnt += 1
else:
cnt -= 1
return x if cnt and nums.count(x) > n // 2 else -1
java
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(List<Integer> nums) {
// write your code here
int candidate = -1;
int count = 0;
for (Integer num : nums) {
if (count == 0) {
candidate = num;
}
if (num == candidate) {
count++;
} else {
count--;
}
}
count = 0;
int length = nums.size();
for (int num : nums) {
if (num == candidate) {
count++;
}
}
return count * 2 > length ? candidate : -1;
}
}
C
class Solution {
public:
int majorityNumber(vector<int>& nums) {
int candidate = -1;
int count = 0;
for (int& num : nums) {
if (count == 0) {
candidate = num;
}
if (num == candidate) {
count++;
} else {
count--;
}
}
count = 0;
int length = nums.size();
for (int& num : nums) {
if (num == candidate) {
count++;
}
}
return count * 2 > length ? candidate : -1;
}
}