数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
}
};
排序后数组的中位数一定是出现次数超过一半的数。
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> ump;
for (int i : nums)
if (++ump[i] > nums.size() / 2) return i;
return -1;
}
};
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candi = 0, counter = 0;
for (int i : nums) {
if (!counter) {
candi = i;
counter = 1;
} else {
if (candi == i) counter++;
else counter--;
}
}
return candi;
}
};
相同的增加,不同的抵消,最后肯定是出现次数超过半数的留下来。
原文:https://www.cnblogs.com/tmpUser/p/14476636.html