• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
229. Majority Element II -- 找出数组中出现次数超过 ⌊ n/3 ⌋ 次的数

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.

class Solution {

public:



    //O(n) Space compexity

    vector<int> majorityElement01(vector<int>& nums) {

        vector<int> result;

        unordered_map<int, int> counts;

        int n = nums.size();

        for(auto item : nums){

            counts[item]++;

            if (counts[item] > n/3 ){

               result.push_back(item); 

               counts[item] = -n; // Tricky: make sure the item only can be put into result once.

            } 

        }

        return result;

    }

    //We know, there could be at most two numbers can be more than 1/3

    //so, same as Majority Element I problem, we can have two counters.

    vector<int> majorityElement02(vector<int>& nums) {

        if(nums.size()<=1) return nums;

        

        //the same algorithm as Majority Element I problem

        int majority1=0, majority2=0, cnt1=0, cnt2=0;

        for(auto item: nums) {

            if (cnt1 == 0 && majority2 != item ) {

                majority1 = item;

                cnt1 = 1;

            } else if (majority1 == item) {

                cnt1++;

            } else if (cnt2 == 0) {

                majority2 = item;

                cnt2 = 1;

            } else if (majority2 == item) {

                cnt2++;

            } else {

                cnt1--;

                cnt2--;

            }

        }

        //re-check it again, in case there has less than two numbers of majority

        cnt1 = cnt2 = 0;

        for (auto item : nums) {

            if (majority1 == item) cnt1++;

            else if (majority2 == item) cnt2++;

        }

        vector<int> result;

        if (cnt1 > nums.size()/3) result.push_back(majority1);

        if (cnt2 > nums.size()/3) result.push_back(majority2);

        return result;

    }

 

posted on 2016-08-25 17:51  ArgenBarbie  阅读(362)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3