问题是找出数组中是否有整数出现n / 3次以上。 该解决方案基于摩尔的投票算法(如果我们用其他所有不同于e的元素抵消元素e的每次出现,那么如果e是多数元素,它将一直存在到结束。)
findCandidate(a[], size)
1. Initialize index and count of majority element
maj_index = 0, count = 1
2. Loop for i = 1 to size – 1
(a) If a[maj_index] == a[i]
count++
(b) Else
count--;
(c) If count == 0
maj_index = i;
count = 1
3. Return a[maj_index]
现在,我们只需要检查候选元素的计数是否大于n / 2。
在找到多数元素的情况下,可以理解这种找到多数元素的候选者的方式,即,至少重复数比其他元素多的数,即使候选者是一个,但是在此问题中的应用尚不清楚。
根据记录,您从数组中有3个不同的元素,如果从数组中删除它们,则答案不会改变,并且保留2个元素及其计数。
在多数情况下,我们保留一个可以成为多数的候选者,但是为什么在此保留两个,而不管所需更改的次数如何。 例如:对于n = 3/4/5大于1倍,对于n = 6/7/8大于2倍,等等。伪代码如下:
When we encounter a new element, there are 3 cases possible :
1)We don’t have 2 elements yet. So add this to the list with count as 1.
2)This element is different from the existing 2 elements. As we said before, we
have 3 distinct numbers now. Removing them does not change the answer. So
decrements 1 from count of 2 existing elements. If their count falls to 0,
obviously its not a part of 2 elements anymore.
3)The new element is same as one of the 2 elements. Increment the count of that
element.
代码如下:
for (int i = 0; i < n; i++) {
// if this element is previously seen,
// increment count1.
if (first == arr[i])
count1++;
// if this element is previously seen,
// increment count2.
else if (second == arr[i])
count2++;
else if (count1 == 0) {
count1++;
first = arr[i];
}
else if (count2 == 0) {
count2++;
second = arr[i];
}
// if current element is different from
// both the previously seen variables,
// decrement both the counts.
else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
// Again traverse the array and find the
// actual counts.
for (int i = 0; i < n; i++) {
if (arr[i] == first)
count1++;
else if (arr[i] == second)
count2++;
}
if (count1 > n / 3)
return first;
if (count2 > n / 3)
return second;
Consequently, the answer will be one of the 2 elements left behind. If they are
not the answer, then there is no element with count > N / 3
为什么要考虑候选人为二和资格标准?