[leedcode 169] Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

public class Solution {
    public int majorityElement(int[] nums) {
        //如果出现次数大于1/2,最终count的值为正对应的res就是所求
        if(nums==null||nums.length<=0) return 0;
        int res=nums[0];
        int count=1;
        for(int i=1;i<nums.length;i++){
            if(count==0){
                res=nums[i];
                count=1;
            }else if(nums[i]==res){
                count++;
            }else count--;
        }
        return res;
    }
}

 

posted @ 2015-08-02 17:06  ~每天进步一点点~  阅读(86)  评论(0编辑  收藏  举报