LC169-多數元素
阿新 • • 發佈:2021-07-09
169. 多數元素
法1:(投票演算法)
//投票演算法
class Solution {
public:
int majorityElement(vector<int>& nums) {
int r, c = 0;
for (auto x: nums)
if (!c) r = x, c = 1;
else if (r == x) c ++ ;
else c -- ;
return r;
}
};
法2:雜湊表統計暴力做法:
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); unordered_map<int,int>cnt; for(auto c:nums){ cnt[c]++; if(cnt[c] > n / 2)return c; } return -1; } };
法3:位運算
class Solution { public: int majorityElement(vector<int>& nums) { int ans = 0; for(int i = 0; i < 32; ++i){ int cnt = 0; for(auto& x : nums) cnt += (x >> i) & 1; //位運演算法統計每個位置上1出現的次數,每次出現則ones+1 ans += (cnt > nums.size() / 2) << i ; //如果1出現次數大於1/2陣列的長度,1即為這個位置的目標數字 } return ans; } };