(5/31/16)Leetcode 169. Majority Element

Easy, 用时3分钟
解法一:
算法名称为Boyer–Moore majority vote algorithm

  1. Eliminate all elements except one.
    Iterating through the array of numbers, maintain a current candidate and a counter initialized to 0. With the current element x in iteration, update the counter and (possibly) the candidate:
    If the counter is 0, set the current candidate to x and the counter to 1. If the counter is not 0, increment or decrement the counter based on whether x is the current candidate.
  2. Determine if the remaining element is a valid majority element.
    With the candidate acquired in step 1, iterate through the array of numbers and count its occurrences. Determine if the result is more than half of the sequence's length. If so, the candidate is the majority. Otherwise, the sequence doesn't contain a majority.
public class Solution {
    public int majorityElement(int[] nums) {
        if(nums.length == 0) return -1;
        int res = nums[0];
        int count = 0;
        for (int i = 0;i < nums.length; i++){
            if (res == nums[i]) count ++;
            else {
                if (count > 0) count --;
                else res = nums[i];
            }
        }
        return res;
    }
}

解法二:
排序取中间值

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,864评论 0 23
  • 古筝十级已经考完,我却还是只有四五级的水平,甚至这还算高估了自己的。一切似乎又从头来过一样。一个指头一个指头的练,...
    维C牛肉粒阅读 159评论 0 0
  • 用紫色把暗部铺一篇,因为我买的彩色铅笔没有色号,所以我都是在涂色的时候凭感觉选颜色,好不专业,然后又选错色,默默的...
    惠Sunny阅读 1,000评论 3 13
  • 朝门前小路 看一眼 细数桃花又开谢几回 你没有回来 我也不去找你 你的岸 种着别人的风景 此岸,彼岸 隔着一段 不...
    月宛央阅读 137评论 2 6