Majority Element II:求个数多余1/3的元素

来源:互联网 发布:poi设置数据有效性 编辑:程序博客网 时间:2024/06/05 06:43

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.

 

思路:朴素想法肯定是排序后遍历,但是限制了复杂度,所以类似于上提,考虑摩尔投票发。

首先,因为个数要大于三分之一,所以最多只能有两个止痒的元素,可以用反证法证明。

所以遍历两次,第一遍找出最大的两个元素,第二遍检验这两个元素是否满足条件。

class Solution {

    public List<Integer> majorityElement(int[] nums) {

        if(nums.length == 0) return new ArrayList<Integer>();

        ArrayList<Integer> l = new ArrayList<Integer>();

        int majority1 = Integer.MAX_VALUE;

        int majority2 = Integer.MIN_VALUE;

        int count1 = 0;

        int count2 = 0;

        for(int i = 0;i<nums.length;i++){

            if(nums[i]==majority1){

                count1++;

            }else if(nums[i]==majority2){

                count2++;

            }else if(count1==0){

                majority1 = nums[i];

                count1 = 1;

            }else if(count2==0){

                majority2 = nums[i];

                count2 = 1;

            }else{

                count1--;

                count2--;

            }

        }

        count1 = 0;

        count2 = 0;

        for(int e:nums){

            if(majority1==e) count1++;

            if(majority2==e) count2++;

        }

        if(count1>nums.length/3) l.add(majority1);

        if(count2>nums.length/3) l.add(majority2);

        return l;

    }

}

 


原创粉丝点击