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];
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,483评论 0 10
  • 细雨伴春游,花枝溅我衣。 山高云杳杳,偶有唤娘声。 明宫多喧闹,当年殿上争。 君王身后事,已是少人闻。
    玉折兰摧阅读 1,661评论 0 49
  • 继续记录!坚持不懈!坚持是我的硬伤,这次一定要疗伤到痊愈!!!因为我有我的小蜗牛一起!! 回来做记录第二天,因为很...
    烨妈阅读 281评论 0 0
  • 调暗的屏幕里面没有你 可是你发的每一个字都像星星 一闪一闪就像我跳动的心 没遇到你之前 我只想脱贫 遇到你之后 突...
    蓦然_7b5d阅读 205评论 0 0
  • 曾国藩是春秋战国时代曾子的七十世孙。他是中国近代政治家、战略家、理学家、文学家,湘军的创立者和统帅;他因为在学问和...
    般若秋雪阅读 255评论 0 2