2020.7.15
增加了新的方法,使用快排中的Partion函数实现,Partition函数每次会返回排在第j大的数及其位置,在leetcode上的前44个case可以跑通,但是不知道为什么在leetcode上的最后一个case总是超时,由于该方法会改变原始数组的顺序,因此如果不能改变顺序的这种方法不可行,还是应该采用摩尔投票法
class Solution {
public:
int majorityElement(vector<int>& nums) {
return MoreThanHalfNum(nums);
}
int MoreThanHalfNum(vector<int>& nums) {
int middle = nums.size() >> 1;
int start = 0;
int end = nums.size() - 1;
int index = Partition(nums, start, end);
while (index != middle) {
if (index > middle) {
end = index - 1;
index = Partition(nums, start, end);
}
else {
start = index + 1;
index = Partition(nums, start, end);
}
}
int result = nums[middle];
return result;
}
//使主元排在第j位
int Partition(vector<int>& nums,int s, int e) {
int index = (rand() % (e - s + 1)) + s;
swap(nums[index], nums[s]);
int i = s + 1, j = e;
while (true) {
while (i <= j && nums[i] <= nums[s]) i++;
while (i <= j && nums[j] >= nums[s]) j--;
if (i > j) break;
swap(nums[i], nums[j]);
}
swap(nums[j], nums[s]);
return j;
}
};
解题思路
利用题目所给数组特性,所求元素在数组中出现次数超过一半
设置两个变量:
result//记录当前元素值
times//记录次数
当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数+1;如果下一个数字和我们之前保存的数字不同,则次数-1.如果次数为0,那么我们需要保存下一个数字
,并把次数设为1.
代码
class Solution
{
public:
int majorityElement(vector<int>& nums) {
int result=nums[0];
int times = 1;
for (vector<int>::iterator it=nums.begin()+1;it!=nums.end();it++)
{
//次数为0,则更新result
if (times == 0) {
result = *it;
times = 1;
}
//相等,次数+1
else if(result==*it)
{
times++;
}
//不相等,次数-1
else
{
times--;
}
}
return result;
}
};