您的位置:首页 > 其它

169. Majority Element

2016-05-17 15:52 316 查看

169. Majority Element

Description:

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Link:

https://leetcode.com/problems/majority-element/

Analysis:

这道题在《编程之美》的2.3寻找发帖“水王” 有出现,里边讲的很好。

对于ARRAY中的一个数K,确定其占到总数的一半以上,现在需要找出这个数K。

1.首先想到的方法肯定就是排序了,然后这个有序的ARRAY中第N/2项一定就是我们要找的数K。其时间复杂度为O(N*log2N+N)。

2.另外一种方法:对这个ARRAY每次删除两个不同的ID(不管是否包含要找的数K),那么剩下的ARRAY中,K出现的次数依然占总数的一半以上。下面证明一下:

删除前:n(K) >= N/2;
删除后:n(K) >= N/2 - 1;
此时K所占的比例:p(K) = n(K)/(N-2) >= (N/2 - 1)/(N-2) = 1/2


好,这样我们可以不断重复删数的过程,减小样本数,从而得到问题的答案。

Source Code(C++):

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

/*************************先进行排序,取中位数*************************************/
/*
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums.at(nums.size()/2);
}
};
*/

/*****************************不断减小样本数量的方法*************************************/
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate;
int ncounts=0;
for (int i=0; i<nums.size(); i++)
{
if (ncounts == 0) {
candidate = nums.at(i);
ncounts = 1;
}
else {
if (candidate == nums.at(i)) {
ncounts++;
}
else {
ncounts--;
}
}
}
return candidate;
}
};

int main() {
Solution sol;
int a[5] = {1, 2, 3, 2, 2};
vector<int> v(5);
for (int i=0; i<v.size(); i++) {
v.at(i) = a[i];
}
cout << sol.majorityElement(v);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: