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.

答案

class Solution {
    public int majorityElement(int[] nums) {
        int candidate_idx = 0, count = 1;
        for(int i = 1; i < nums.length; i++) {
            if(nums[i] == nums[candidate_idx])
                count++;
            else
                count--;
            if(count == 0) {
                candidate_idx = i;
                count = 1;
            }
        }
        return nums[candidate_idx];
    }
}

你可能感兴趣的:(Majority Element)