日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Leet Code】229. Majority Element II---Medium

發布時間:2023/12/15 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Leet Code】229. Majority Element II---Medium 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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:

  • How many majority elements could it possibly have?Show More Hint?
  • 思路1:

    題目中重點強調出現的次數大于? n/3 ?,所以可能有0個、1個或者2個(最多2個)這樣的數存在,所以只需要設置2個變量cand1,、cand2來記錄出現次數可能大于? n/3 ?的數據,分別用count1和count2記錄數據出現的次數。

    思路2:

    另一種最直接的方法就是用map對數組中每個值出現的次數做記錄,然后把出現次數大于? n/3 ?的值存入返回結果,該方法的缺點是空間復雜度為O(n)。

    代碼1實現:

    class Solution { public:vector<int> majorityElement(vector<int>& nums) {vector<int> result;if(nums.size() < 1) return result;if(nums.size() == 1) return nums;int cand1 = 0, cand2 = 0;int count1 = 0, count2 = 0;//找到滿足條件的數,可能有一個滿足條件的,最多有兩個滿足條件的for(auto num: nums){if (count1 == 0)cand1 = num;else if (count2 == 0)cand2 = num;//處理count的值if(cand1 == num)++count1;else if(cand2 == num)++count2;else{--count1;--count2;}}if(count(nums.begin(), nums.end(), cand1) > nums.size() / 3)result.push_back(cand1);//此處cand1 != cand2一定要判斷,否則對于數組[2,2],就會返回[2,2],而期望的結果是[2]if(cand1 != cand2 && count(nums.begin(), nums.end(), cand2) > nums.size() / 3)result.push_back(cand2);return result;} };
    代碼實現2:

    class Solution { public:vector<int> majorityElement(vector<int>& nums) {map<int, int> myMap;for (auto& num: nums) myMap[num]++;vector<int> res;for (auto it = myMap.begin(); it != myMap.end(); it++) if (it->second > nums.size()/3)res.push_back((*it).first);return res;} };

    總結

    以上是生活随笔為你收集整理的【Leet Code】229. Majority Element II---Medium的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。