求众数 LeetCode

求众数 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--;//不相同,可理解为删除备选元素和当前元素
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值