我正在研究 Boyer-Moore 算法(从这里开始),我有一个快速的问题 - 第二遍需要什么(基本上只是通过找到该元素的频率来“确认”)。第一遍本身不能保证找到的元素是大多数元素吗?我考虑了几个例子,觉得一次通过就足够了。您能否提供一些例子来反驳我的感受?
代码(如果需要)如下:
int majorityElement(vector<int>& nums) {
int candidate=0, count=0;
for(auto value: nums) {
//update the candidate if the count == 0
if(count==0)
candidate=value;
//if the value == candidate then increment count
if(value==candidate)
count++;
else
//decrement count
count--;
}
//return candidate
return candidate;
}
编辑: 如果我理解正确,该算法仅适用于多数元素的频率确实大于(vector size())/2
. 那么,真的需要第二遍吗?每当我们编写代码时,我们都会进行一些琐碎的完整性检查(例如检查输入向量是否为空),那么在这种情况下,为什么我们将“完整性检查”作为算法的一部分呢?或者还有更多的东西吗?