数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2
限制:
1 <= 数组长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
1.利用哈希表统计出现数字的次数
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int> hash;
int res = 0, len = nums.size();
for(int i = 0; i < len; i++){
hash[nums[i]]++;
if(hash[nums[i]] > len/2)
res = nums[i];
}
return res;
}
};
2.利用排序,超过一半的数字一定在数组的最中间
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}
};
3.摩尔投票法,学习思路来自于 Leetcode Krahets大神
https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/mian-shi-ti-39-shu-zu-zhong-chu-xian-ci-shu-chao-3/
class Solution {
public:
int majorityElement(vector<int>& nums) {
//摩尔投票法 因为最多的数字一定多于数组内其他数字,所以遇到该数+1遇到不相等的数-1 当投票为0时,剩余数组内数字的众数也一定多与其他数字。
int vote=0;//投票
int res=0;
for(int i=0;i<nums.size();i++)
{
if(vote==0)res=nums[i];
//如果投票数为0 则设定当前数字为可能最多
if(res!=nums[i])//如果当前数字不等于设定的数字
{
vote--;//投票--
}else//如果相等则++
{
vote++;
}
}
return res;
}
};