题目:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1, 2, 3, 2, 2, 2, 5, 4, 2}
。 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
解析:
此题可以用三种方法进行求解,1、排序后中间元素一定是出现次数超过数组中一半的元素。2、哈希表求解。3、超过一半元素的次数要比其他所有元素总和的次数还要多。
参考答案:
class Solution{
public:
int majorityElement(vector<int> &nums){
//方法1:排序后中间元素一定是出现次数超过数组中一半的元素
sort(nums.begin(), nums.end());
return nums[nums.size() / 2];
//方法2:哈希表
unordered_map<int, int> mp;
for(auto it: nums){
mp[it]++;
if(mp[it] > nums.size() / 2)
return it;
}
return 0;
//方法3:超过一半元素的次数要比其他所有元素总和的次数还要多
int target = nums[0];
int count = 1;
for(int i = 1; i < nums.size(); ++i){
if(target == nums[i])
count++;
else
count--;
if(0 == count){
target = nums[i];
count = 1;
}
}
int times = 0;
for(int i = 0; i < nums.size(); ++i){
if(target == nums[i])
times++;
}
return times > nums.size()/2 ? target : 0;
}
};