前提:此数组不为空,且这样的元素存在
solutions:
分析:可以将数组排序,出现在n/2+1位置的一定是所求。故排序的话也可以只排前n/2+1个。
class Solution {
public:
void quikSort(vector<int>& nums, int low1, int high1) {
//int low=0, high=nums.size();
int low=low1, high=high1;
if(low >= high){
return;
}
int key=nums[low];
while(low < high) {
while(low<high && nums[high]>=key) {
--high;
}
nums[low]=nums[high];
while(low<high && nums[low]<=key) {
++low;
}
nums[high]=nums[low];
}
nums[low]=key;
quikSort(nums, low1, low-1);
quikSort(nums, low+1, high1);
}
void sort(vector<int>& nums) {
quikSort(nums, 0, nums.size()-1);
}
int majorityElement(vector<int>& nums) {
vector<int> V(&nums[0], &nums[nums.size()/2+1]);
sort(V);
return V.back();
}
};
但是在lc上运行超时。
其实存在一个O(n)的算法:
用两个变量,一个计数器count,一个记录出现次数最多的元素result。
从第2个元素开始遍历,和其前一个相等则让count+1,不等则-1,减为0则让result变为当前元素。
result的最终值及为所求。
class Solution {
public:
int majorityElement(vector<int> &nums) {
int result=nums[0];
int count=1;
for(int i=1; i<nums.size(); ++i) {
if(nums[i] == result) {
++count;
}
else {
--count;
if(count == 0) {
result=nums[i];
++count;
}
}
}
return result;
}
};
还有大侠想出来了随机数的算法:http://www.cnblogs.com/fanyabo/p/4178993.html
class Solution {
public:
int majorityElement(vector<int> &num) {
int count = 0;
for(;;) {
if(num.size() == 1)
return num[0];
else {
int i = rand() % (num.size() - 1);
for(int j = 0; j < num.size(); j++) {
if(num[j] == num[i])
count++;
}
if(count > (num.size() / 2))
return num[i];
else {
count = 0;
continue;
}
}
}
}
};