LeetCode Majority Element II(Moore Voting Algorithm即Majority Voting Algorithm)



Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

题意:给出一个数组,求出现次数大于n/3的元素,要求时间复杂度为O(n),空间复杂度为O(1)

思路:用Majority Voting Algorithm的一般算法

          1、候选者的个数为2,计数数组的元素个数也为2

           2、在遍历时,如果候选者中没有包含,就将其插入,如果包含,将计数加1,如果没有包含,将所有候选者的计数减1

           3、第二次遍历时,统计个数,判断出现次数是否满足要求

代码如下:

class Solution
{
    public List<Integer> majorityElement(int[] nums)
    {
        List<Integer> res = new ArrayList<Integer>();

        if (nums.length == 0) return res;
        else return __majorityElement(nums, 3);
    }

    private List<Integer> __majorityElement(int[] nums, int k)
    {
        int cnt = k - 1;
        ArrayList<Integer> candidates = new ArrayList<Integer>();
        ArrayList<Integer> count = new ArrayList<Integer>();

        for (int i = 0; i < cnt; i++)
        {
            candidates.add(0);
            count.add(0);
        }

        for (int num : nums)
        {
            boolean found = false;
            for (int i = 0; i < cnt; i++)
            {
                if (count.get(i) == 0 || candidates.get(i) == num)
                {
                    int c = count.get(i);
                    count.set(i,c + 1);
                    candidates.set(i, num);
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                for (int i = 0; i < cnt; i++)
                {
                    int c = count.get(i);
                    count.set(i, c - 1);
                }
            }
        }

        Collections.fill(count, 0);
        for (int num : nums)
        {
            for (int i = 0; i < cnt; i++)
            {
                if (candidates.get(i) == num)
                {
                    int c = count.get(i);
                    count.set(i, c + 1);
                    break;
                }
            }
        }

        List<Integer> ans = new ArrayList<Integer>();
        for (int i = 0; i < cnt; i++)
        {
            if (count.get(i) > nums.length / k)
            {
                ans.add(candidates.get(i));
            }
        }

        return ans;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

kgduu

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

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

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

打赏作者

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

抵扣说明:

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

余额充值