#169 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.
Input: [3,2,3] Output: 3
Input: [2,2,1,1,1,2,2] Output: 2
1、利用快排每次对传入的nums[low]进行排序,找到其对应位置index的思想。同时考虑到因为肯定会超过n/2,那么排序后的中位数对应的肯定就是结果了。
写快排部分,很容易错的几个部分。第一个low<high,则return;第二个是交换后要记得first++或last--;第三个取出的temp是nums[low]而不是nums[0]。
class Solution {
public:
int QuickSort(vector<int>&nums, int first, int last)
{
int temp = nums[first]; //不是0
while (first<last)
{
while (first<last&&nums[last] >= temp)
last--;
if (first<last)
nums[first++] = nums[last];
while (first<last&&nums[first]<temp)
first++;
if (first<last)
nums[last--] = nums[first];
}
nums[last] = temp;
return last;
}
int majorityElement(vector<int>& nums) {
//因为超过一半,因此排序后索引为n/2的数字则为该数。
//同时又避免全部排序,可以采用快排的思想
if (nums.empty())
return 0;
int index = QuickSort(nums, 0, nums.size() - 1);
while (index != (nums.size() - 1) / 2)
{
if (index == (nums.size() - 1) / 2)
return nums[index];
else if (index>(nums.size() - 1) / 2)
index = QuickSort(nums, 0, index - 1);
else
index = QuickSort(nums, index + 1, nums.size() - 1);
}
return nums[index];
}
};
2、利用哈希表
因为不需要索引什么,所以直接就counts[键值]++去赋值value;
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> counts;
int n = nums.size();
for (int i = 0; i < n; i++)
if (++counts[nums[i]] > n / 2)
return nums[i];
}
};
3、摩尔投票算法
遍历数字,保存两个值。一个是数组中的当前可能为最大的数字temp,一个是次数。初始化temp为第一个数,然后从1开始遍历,如果遍历的数和temp一样,则次数+1,如果不一样,则-1;当次数为0,则更新temp为当前数,并设置次数为1。如此循环,因为我们要找的数比其他数字都要多,则次数肯定是>0的,也就是temp最后一定会是该最大的数。
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;
}
};