【Leet Code】229. Majority Element II---Medium
生活随笔
收集整理的這篇文章主要介紹了
【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:
思路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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 英语分词_英文分词算法(P
- 下一篇: 1.2 LaTex排版