add: 220221 [cpp]

This commit is contained in:
Lam Haoyin 2022-02-22 00:29:46 +08:00
parent cf70fcd0dd
commit 5c8f652039
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 25 additions and 1 deletions

24
cpp/2202/220221.cpp Normal file
View File

@ -0,0 +1,24 @@
#include <vector>
#include <unordered_map>
/**
* 169. Majority Element
* Given an array nums of size n, return the majority element.
* The majority element is the element that appears more than n / 2 times. You may assume that the majority element always exists in the array.
*/
class Solution {
public:
static inline int majorityElement(const std::vector<int>& nums) {
int n = nums.size() >> 1;
std::unordered_map<int, int> m;
for (int i : nums)
if (++m[i] > n)
return i;
return 0;
}
};
int main() {
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2202)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2202 220221-CN.cpp) ADD_EXECUTABLE(2202 220221.cpp)