剑指 Offer 39. 数组中出现次数超过一半的数字

62 篇文章 1 订阅
39 篇文章 0 订阅

剑指 Offer 39. 数组中出现次数超过一半的数字

链接

添加链接描述
可借鉴的排序

思路

map

遍历数组,同时用一个map的键来存储数组中出现的数,用map的值来存储数的出现次数,最后,遍历map,如果map中某个键对应的值超过了数组的一半,则将其返回,由于题目设置,势必存在,在循环外返回-1(即数组中没有一个数出现次数超过数组中数字的一半)

摩尔投票

遍历数组,如果count 为0,则将该数赋值给card,然后遍历之后的数字,相同则加1,不同则减一,遍历完成之后,card 即为数组中超过板书的数字

排序

先将数组进行排序,然后返回中间元素

代码

map

在这里插入图片描述

class Solution {
    public int majorityElement(int[] nums)
    {
        Map<Integer, Integer> map = new TreeMap<>();

        for (int num : nums)
        {
            if (!map.containsKey(num))
            {
                map.put(num, 0);
            } else
            {
                map.put(num, map.get(num) + 1);
            }
        }
        //
        int n = nums.length / 2;
        for (int num : nums)
        {
            if (map.get(num) >= n)
            {
                return num;
            }
        }
        return -1;
    }
}

摩尔投票

在这里插入图片描述

class Solution {
    public int majorityElement(int[] nums)
    {
        if (nums.length <= 0)
        {
            return -1;
        }
        int count = 0;
        Integer card = null;
        for (int num : nums)
        {
            if (0 == count)
            {
                card = num;
            }
            count += (card == num) ? 1 : -1;
        }
        return card;
    }
}

排序

在这里插入图片描述

class Solution {
    public int majorityElement(int[] nums)
    {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枳洛淮南✘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值