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

来源:互联网 发布:如何购买域名 编辑:程序博客网 时间:2024/05/12 17:46


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
原创粉丝点击