首页 > 其他 > 详细

229. Majority Element II

时间:2018-06-26 10:28:56      阅读:176      评论:0      收藏:0      [点我收藏+]

问题描述:

Given an integer array of size n, find all elements that appear more than ? n/3 ? times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]

 

解题思路:

由于要求我们用O(1)的空间复杂度,那我们可以类比169. Majority Element

使用摩尔投票法。

出现个数大于n/3最多有两个数字:将数组等份分成3份,若要大于n/3,那么可以有两份分别为一个数字,同时再从第三份里取至少一个数字。

所以我们可以用摩尔投票法先找到这两个,然后再循环一遍确认个数是否满足条件

 

代码:

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> ret;
        int can1 = 0, can2 = 0;
        int cnt1 = 0, cnt2 = 0;
        for(int n:nums){
            if(n == can1) cnt1++;
            else if(n == can2) cnt2++;
            else if(cnt1 == 0) {
                can1 = n;
                cnt1 = 1;
            }else if(cnt2 == 0){
                can2 = n;
                cnt2 = 1;
            }else{
                cnt1--;
                cnt2--;
            }
        }
        cnt1 = 0;
        cnt2 = 0;
        for(int n : nums){
            if(n == can1)cnt1++;
            else if(n == can2) cnt2++;
        }
        int stdNum = nums.size()/3;
        if(cnt1 > stdNum) ret.push_back(can1);
        if(cnt2 > stdNum) ret.push_back(can2);
        return ret;
    }
};

 

229. Majority Element II

原文:https://www.cnblogs.com/yaoyudadudu/p/9227164.html

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