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

【LeetCode】229. Majority Element II

时间:2015-07-08 20:28:29      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

Majority Element II

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?
  2. Do you have a better hint? Suggest it!

 

超过⌊ n/k ⌋ 最多有(k-1)个结果。k=3时最多2个结果。

因此设置两个candidate进行判断。

注意:留到最后的candidate不代表真正的结果。举例[3,2,3],2是candidate但不是结果。

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> ret;
        if(nums.empty())
            return ret;
        int candidate1 = nums[0];
        int count1 = 1;
        int candidate2 = nums[0];
        int count2 = 0;
        for(int i = 1; i < nums.size(); i ++)
        {
            if(count1 != 0 && count2 != 0)
            {
                if(nums[i] == candidate1)
                    count1 ++;
                else if(nums[i] == candidate2)
                    count2 ++;
                else
                {
                    count1 --;
                    count2 --;
                }
            }
            else if(count1 != 0 && count2 == 0)
            {
                if(nums[i] == candidate1)
                    count1 ++;
                else
                {
                    candidate2 = nums[i];
                    count2 = 1;
                }
            }
            else if(count1 == 0 && count2 != 0)
            {
                if(nums[i] == candidate2)
                    count2 ++;
                else
                {
                    candidate1 = nums[i];
                    count1 = 1;
                }
            }
            else
            {
                candidate1 = nums[i];
                count1 = 1;
            }
        }
        if(count1 != 0)
        {
            count1 = 0;
            for(int i = 0; i < nums.size(); i ++)
            {
                if(nums[i] == candidate1)
                    count1 ++;
            }
            if(count1 > nums.size()/3)   
                ret.push_back(candidate1);
        }
        if(count2 != 0)
        {
            count2 = 0;
            for(int i = 0; i < nums.size(); i ++)
            {
                if(nums[i] == candidate2)
                    count2 ++;
            }
            if(count2 > nums.size()/3)   
                ret.push_back(candidate2);
        }
        return ret;
    }
};

技术分享

【LeetCode】229. Majority Element II

标签:

原文地址:http://www.cnblogs.com/ganganloveu/p/4630978.html

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