多数元素-投票算法

    //    多数元素
    //    输入:nums = [2,2,1,1,1,2,2]
    //    输出:2
    //  投票算法
    public static int majorityElement(int[] nums){
        //  更新多的元素状态
        int count=0;
        //选举结果
        Integer candidate=null;
        for (int num:
             nums) {
        // 选出不同的多的元素
            if(count==0){
                candidate=num;
            }
        //  num==candidate都是相同的,num!=candidate出现不同的
            count+=(num==candidate)?1:-1;
        }
        return candidate;
    }

你可能感兴趣的:(算法,面试,java,算法,数据结构)