求众数 LeetCode
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
题意:给一个大小为n的数列,查找它的主要数,主要数是指在数列中出现超过 ⌊ n/2 ⌋个的数字。题目保证该主要数存在且数列非空。
方法一:对数列进行排序,则第n/2位置上的数字显然为主要数。假设数组长度为10,则主要数至少出现6次,则num[5]必为主要数。
方法二:使用map对每个数字出现的次数进行统计,若出现某个数字出现的次数超过n/2次,即返回该数字。代码如下
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
int majorityElement(vector<int>& nums) {
if(nums.size() == 1)
return nums[0];
map<int,int> ans;
for (int i = 0; i < nums.size(); ++i) {
if(ans.count(nums[i])){ //存在这个关键值则返回1,否则返回0;
ans[nums[i]]++;
if(ans[nums[i]] > nums.size()/2)
return nums[i];
} else{
ans[nums[i]] = 1;
}
}
}
};
方法三:摩尔投票法
在每一轮投票过程中,从数组中找出一对不同的元素,将其从数组中删除。这样不断的删除直到无法再进行投票,如果数组为空,则没有任何元素出现的次数超过该数组长度的一半。如果只存在一种元素,那么这个元素则可能为目标元素。
//java
public int majorityElement(int[] nums) {
int majority = -1;
int count = 0;
for (int num : nums) {
if (count == 0) {//表示截至到当前数组,无候选元素。
majority = num;
count++;
} else {
if (majority == num) {//相同则加一
count++;
} else {
count--;//不相同,可理解为删除备选元素和当前元素
}
}
}