码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Majority Element

时间:2015-07-20 16:32:57      阅读:126      评论: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.

思路分析:求主元素的经典算法是Moore投票算法,基本可以理解为将主元素和不同元素一一对应相消,最后剩下来的元素就是主元素。具体做法是,初始计数器times和candidate都是0,然后遍历数组,当times为0时置换新的candidate,遇到和candidate相同元素times++,遇到和candidate相异元素times--,如此操作,如果主元素存在,最后剩下的一定是主元素。时间复杂度O(n),空间复杂度O(1).

AC Code

public class Solution {
    public int majorityElement(int[] nums) {
        //0627
        //Moore Voting 
        int n = nums.length;
        
        int candidate = 0;
        int times = 0;
        for(int i = 0; i < n; i++){
            if(times == 0) candidate = nums[i];
            if(nums[i] != candidate){
                times--;
            } else{
                times++;
            }
        }
        return candidate;
        //0631
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode Majority Element

标签:

原文地址:http://blog.csdn.net/yangliuy/article/details/46968121

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!