[Leetcode]_169 Majority Element

/**
*  Index: 169
*  Title: Majority Element
*  Author: ltree98
**/


题意

• 最频繁的元素出现次数将大于一半数组长度

我的

思路

std::sort会根据数据量改变算法，达到平均时间复杂度为 O(nlogn)

实现

class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[int(nums.size()/2)];
}
};


进阶

随机

class Solution {
public:
int majorityElement(vector<int>& nums) {
int len = nums.size();
srand(unsigned(time(NULL)));
while (true) {
int index = rand() % len;
int aim = nums[index];
int counts = 0;
for (int i = 0; i < len; i++)
if (nums[i] == aim)
counts++;
if (counts > len / 2)
return aim;
}
}
};


分治

class Solution {
public:
int majorityElement(vector<int>& nums) {
return majority(nums, 0, nums.size() - 1);
}

private:
int majority(vector<int>& nums, int left, int right)    {
if(left == right)
return nums[left];

int mid = left + (right - left) / 2;
int leftMid = majority(nums, left, mid);
int rightMid = majority(nums, mid + 1, right);

if(leftMid == rightMid)
return leftMid;

int leftMidCount = count(nums.begin() + left, nums.begin() + right + 1, leftMid);
int rightMidCount = count(nums.begin() + left, nums.begin() + right + 1, rightMid);

if(leftMidCount > rightMidCount)
return leftMid;
else
return rightMid;
}
};


摩尔投票

class Solution {
public:
int majorityElement(vector<int>& nums) {
int major, counts = 0, n = nums.size();
for (int i = 0; i < n; i++) {
if (!counts) {
major = nums[i];
counts = 1;
}
else counts += (nums[i] == major) ? 1 : -1;
}
return major;
}
};


位操作

class Solution {
public:
int majorityElement(vector<int>& nums) {
int major = 0, n = nums.size();
for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) {
int bitCounts = 0;
for (int j = 0; j < n; j++) {
if (nums[j] & mask) bitCounts++;
if (bitCounts > n / 2) {
major |= mask;
break;
}
}
}
return major;
}
};


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客