首页 > 其他 > 详细

Leetcode 169 Majority Element

时间:2015-06-24 20:55:18      阅读:204      评论:0      收藏: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.

 

Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:

If the counter is 0, we set the current candidate to x and the counter to 1.

If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.

After one pass, the current candidate is the majority element. Runtime complexity = O(n).

var majorityElement = function(nums) {
    var candidate = 0
    var checker = 0
    for(var i=0;i<nums.length;i++){
        if(checker===0){
            candidate = nums[i]
            checker++
        }
        else{ 
            if(nums[i] === candidate)
                checker++
            else
                checker--
        }
    }
    return candidate
}

 

Leetcode 169 Majority Element

原文:http://www.cnblogs.com/lilixu/p/4598481.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!