美文网首页
Majority Element

Majority Element

作者: BLUE_fdf9 | 来源:发表于2018-10-31 10:59 被阅读0次

    题目
    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

          本文链接:https://www.haomeiwen.com/subject/ushotqtx.html