Majority Element

2018-10-31  本文已影响0人  BLUE_fdf9

题目
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];
    }
}
上一篇下一篇

猜你喜欢

热点阅读