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.
Credits:Special thanks to @ts for adding this problem and creating all test cases.

public class Solution {
    public int majorityElement(int[] nums) {
        int candidate = 0;
        int count = 0;
        for(int i=0;i<nums.length;i++)
        {
            if(count == 0)
            {
                candidate = nums[i];
                count = 1;
            }
            else
            {
                if(nums[i] == candidate)
                  count++;
                else
                  count--;
            }
        }
        return candidate;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,884评论 0 23
  • Given an array of size n, find the majority element. The ...
    六尺帐篷阅读 324评论 0 1
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 我骑着电车看着南面的门市。孩子的学习机充电器找不到了,我想给她再买一个。街道很宽,车流很大,显着拥挤。四周的大厦,...
    问芯阅读 359评论 8 7
  • 印刷术虽然是很具天才的发明,但和文字的发明比起来则相形见拙。……这是一项为利至溥的发明,可以延续有关过去时代的记忆...
    ianwest阅读 1,831评论 4 1