Majority Element
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.
自己一开始随便写了一个用map的解法
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int> m;
for(int i=0;i<nums.size();i++){
if(m.find(nums[i])==m.end())m[nums[i]]=1;
else m[nums[i]]++;
if(m[nums[i]]>nums.size()/2) return nums[i];
}
return 0;
}
};
后来看主流解法主要如下:
1、就这个问题而言,有一种算法叫 Moore’s Voting Algorithm,由Robert S.Boyer 和J Strother Moore于1980年发明,是线性时间复杂度。空间O(1)。
public class Solution {
public int majorityElement(int[] num) {
int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;
}
return major;
}
}
2、随机挑选一个值,检测是否为最多值。
class Solution {
2 public:
3 int majorityElement(vector<int> &num) {
4
5 int count = 0;
6
7 for(;;) {
8 if(num.size() == 1)
9 return num[0];
10 else {
11 int i = rand() % (num.size() - 1);
12 for(int j = 0; j < num.size(); j++) {
13 if(num[j] == num[i])
14 count++;
15 }
16 if(count > (num.size() / 2))
17 return num[i];
18 else {
19 count = 0;
20 continue;
21 }
22 }
23 }
24 }
};
3、sort之后找最长的一段。这个方法……总觉得不太优呢。不过很便利就是了。
class Solution {
public:
int majorityElement(vector<int> &num) {
int n = num.size();
sort(num.begin(),num.end());
return num[n/2];
}
};
还有暴力破解法等等……Leetcode建议解决方法如下:
接下来就是这道题的变种229. Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times. The algorithm should run in linear time and in O(1) space.
基本上就是要求你用Moore voting system来做了。
class Solution {
public:
vector<int> majorityElement(vector<int>& nums) {
int a=0,b=1,ac=0,bc=0;//注意ab初始值不能一样
for(auto n: nums){
if(n==a)ac++;
else if(n==b)bc++;
else if(ac==0){a=n;ac++;}
else if(bc==0){b=n;bc++;}
else {ac--;bc--;}
}
ac=bc=0;
for(auto n: nums){
if(n==a)ac++;
if(n==b)bc++;
}
vector<int>r;
if(ac>nums.size()/3) r.push_back(a);
if(bc>nums.size()/3) r.push_back(b);
return r;
}
};