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

    [原]LeetCode Majority Element II

    yangliuy发表于 2015-07-20 15:10:04
    love 0

    Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

    Hint:

    1. How many majority elements could it possibly have?
    思路分析:这题是Majority Element的扩展,同样可以采用Moore投票法解决。首先需要分析,如果这样的元素(elements that appear more than ⌊ n/3 ⌋ times)存在,那么一定不会超过两个,证明用反证法很容易理解。接下来就是如何找出这可能的两个元素。可以分两步,找两个candidate和验证candidate出现的次数是否超过⌊ n/3 ⌋ times。 找两个候选candidate的方法就是Moore投票法,和Majority Element中类似。需要验证的原因是,不同于Majority Element中已经限制了主元素一定存在,这题不一定存在这样的元素,即使存在个数也不确定,所以需要验证过程。时间复杂度O(n),空间复杂度O(1).
    AC Code:
    public class Solution {
        public List<Integer> majorityElement(int[] nums) {
            //moore voting
            //0632
            int candidate1 = 0, candidate2 = 0, times1 = 0, times2 = 0;
            int n = nums.length;
            for(int i = 0; i < n; i++){
                if(nums[i] == candidate1) {
                    times1++;
                } else if(nums[i] == candidate2){
                    times2++;
                } else if(times1 == 0) {
                    candidate1 = nums[i];
                    times1 = 1;
                } else if(times2 == 0){
                    candidate2 = nums[i];
                    times2 = 1;
                } else{
                    times1--;times2--;
                }
            }
            
            times1 = 0; times2 = 0;
            for(int i = 0; i < n; i++){
                if(nums[i] == candidate1) times1++;
                else if(nums[i] == candidate2) times2++;
            }
            
            List<Integer> res = new ArrayList<Integer>();
            if(times1 > n/3) {
                res.add(candidate1);
            }
            if(times2 > n/3) {
                res.add(candidate2);
            }
            return res;
            //0649
        }
    }




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