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.
题目大意:
给定一个数组,数组的长度是n,找出出现次数超过n/2的元素。
这里给出两种解法:
我们可以使用map来记录每个元素出现的次数,如果在统计元素出现个数的时候,当前元素出现的次数超过n/2那么直接返回该结果即可。
另一种做法,不需要使用map,试想,如果一个元素的出现次数超过n/2,假设这个元素是x,那么每个x对应一个非x元素,两个互相消除,可以联想一下“开心消消乐” 。在最后一定至少剩余一个x。那么程序该如何实现呢,首先我们先假设第一个元素就是出现次数超过n/2的那个元素,并且我们记录它当前出现的次数,如果下一个元素和这个元素不一样,那么这两个元素就相互抵消,我们记录的出现次数就减1,当然如果一样的话就加1。如果我们的记录次数变成0,就要将下一个元素看作是超过n/2次的元素,进行同样的操作,直到全部抵消。
题目代码:
class Solution {
public:
int majorityElement(vector<int>& nums) {
int ans = nums[0];
int cnt = 1;
for(int i = 1; i < nums.size(); i++){
if(cnt == 0){
ans = nums[i];
cnt++;
}else if(nums[i] == ans){
cnt++;
}else{
cnt--;
}
}
return ans;
}
};
class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int,int> m;
for(int i = 0; i < nums.size(); i++){
m[nums[i]]++;
if(m[nums[i]] > nums.size()/2){
return nums[i];
}
}
}
};