</pre><p></p><p>【题目】Given an array of size n, find the majority element.The majority element is the element that appears more than. You may assume that the array is non-empty and the majority element always exist in the array.给定一个大小为n的数组,找出其中出现次数超过n/2的元素。(假设其一定存在)</p><p></p><p>【解析】愚蠢如我,程序如下,不解释:</p><p></p><pre name="code" class="cpp">int majorityElement(int* nums, int numsSize) {
int n = 0;
for(int i = 0; i < numsSize; i++){
for(int j = 0;j < numsSize;j++){
if(nums[i] == nums[j]) n++;
}
if(n>numsSize/2) return nums[i];
else n = 0;
}
}
做了一些测试,加上人脑验算了几遍,正确性应该没有问题。然而这种大量消耗时间按复杂度的程序,一律以错误论处。
6 Suggested Solutions in C++ with Explanations
这篇文章中,详细阐释了该题的6种解法,下文将以翻译为主。
文章第一句话就形容了我的算法:
Well, if you have got this problem accepted, you may have noticed that there are 7 suggested solutions for this problem. The following passage will implement 6 of themexcept the O(n^2)brute force algorithm
1. Hash Table 哈希表
哈希表解法是最直接的。我们可以从每个元素及其出现次数中获得一个