剑指 Offer 39. 数组中出现次数超过一半的数字

package leetcode;

public class offer_39 {
    public int majorityElement(int[] nums) {
        int target=nums[0];
        int count=0;
        //相同count就减一,不同则加一,因为target总存在,所以最后剩下的就是target
        for(int i=0;i<nums.length;i++) {
            if(count==0) {
                target=nums[i];
                count=count+1;
            }
            else {
                if(target==nums[i]) {
                    count=count+1;
                }else {
                    count=count-1;
                }
            }
        }
        return target;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        offer_39 off=new offer_39();
        int[] nums= {1, 2, 3, 2, 2, 2, 5, 4, 2};
        System.out.println(off.majorityElement(nums));
    }

}

 

posted on 2022-03-24 09:56  一仟零一夜丶  阅读(22)  评论(0)    收藏  举报