您的位置:首页 > 其它

(LeetCode 169) Majority Element

2015-05-03 11:40 453 查看
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.

题目:

给一数组,找出数组中的众数,众数就是出现的次数大于其他所有数出现次数之和。

假设数组不为空,且众数一定存在

思路:

方法1:hashmap

通过遍历数组,将数组每个数都通过hashmap来统计其出现的个数,如果某个数个数超过一半,则为众数。

时间空间复杂度均为O(n)

方法2:Moore Voting Algorithm

众数存在的情况下,每次扔掉两个不同的数,众数不变,最终剩下的数一定是众数。

扔掉一个众数和一个非众数,众数不变

扔掉两个非众数,众数不变

时间复杂度O(n),空间复杂度O(1)

方法3:Partition

如果数组是有序的,如果存在众数,那么中位数一定是众数,因此可以通过类似快排的partition过程来查找中位数。

代码:

#include <iostream>
#include <vector>
#include <math.h>
#include <map>

using namespace std;

class Solution {
public:
// hash_map method
int majorityElement1(vector<int> &num) {
int n =num.size();
if(n==1) return num[0];
map<int,int> m;
for(vector<int>::iterator it=num.begin();it!=num.end();it++){
m[*it]+=1;
if(m[*it] > floor(n/2))
return *it;
}
}

// moore voting algorithm
int majorityElement2(vector<int> &num){
int n=num.size();
if(n==1) return num[0];
int count=0;
int x;
for(int i=0;i<n;i++){
if(count==0){
x=num[i];
count=1;
}
else if(x==num[i])
++count;
else
--count;
}

return x;
}

int partition(vector<int> &num,int left,int right){
int key=num[left];
int i=left;
int j=right;
while(i<j){
while(i<j && num[j]>=key) j--;
if(i<j) num[i++]=num[j];
while(i<j && num[i]<=key) i++;
if(i<j) num[j--]=num[i];
}
num[i]=key;
return i;
}

// partition method
int majorityElement3(vector<int> &num){
int n=num.size();
int left=0;
int right=n-1;
int middle=n>>1;
int index;
index=partition(num,left,right);
while(index!=middle && left<right){
if(index>middle){
right=index-1;
index=partition(num,left,right);
}
else{
left=index+1;
index=partition(num,left,right);
}
}

int count=0;
for(int i=0;i<n;i++){
if(num[i]==num[index]) count++;
}
if(count>floor(n/2))
return num[index];
return -1;
}

};

int main()
{
int a[]={2,3,2,2,4,3,3,3,3};
int n=sizeof(a)/sizeof(a[0]);
vector<int> num(a,a+n);
Solution s;
cout << s.majorityElement3(num)<< endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: