229. Majority Element II

来源:互联网 发布:mac 桌面便签 新建 编辑:程序博客网 时间:2024/06/06 20:21

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.

当符合条件的数是两个的情况下,显然两个candi都是对的

是一个的情况下 在最差的情况中,第一个cand也会被保留,因为如果不保留 则出现amo1-- amo2--的数量要比cand1++多 那么发生交换/发生cand2++的次数要大于等于amo1-- amo2--的次数要大于cand1++的次数 这样次数总计要大于100% 产生矛盾

public class Solution {    public List<Integer> majorityElement(int[] nums) {        //可能有0-2个这样的数        int cand1=0,cand2=0,amo1=0,amo2=0;        int i = 0;        while(i<nums.length){            if(nums[i]==cand1){                amo1++;            }else if(nums[i]==cand2){                amo2++;            }else if(amo1==0){                amo1++;                cand1=nums[i];            }else if(amo2==0){                amo2++;                cand2=nums[i];            }else{                amo1--;                amo2--;            }            i++;        }                i=0;        int numC1 = 0, numC2 = 0,C = 0;        for(;i<nums.length;i++){            if(nums[i]==cand1)numC1++;            if(nums[i]==cand2)numC2++;            C++;        }        List<Integer> ret = new ArrayList<>();        if(numC1>C/3)ret.add(cand1);        if(numC2>C/3&&cand1!=cand2)ret.add(cand2);        return ret;    }}

0 0