IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]LeetCode Majority Element

    yangliuy发表于 2015-07-20 14:58:41
    love 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
        }
    }




沪ICP备19023445号-2号
友情链接