-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode169.cpp
More file actions
41 lines (37 loc) · 925 Bytes
/
leetcode169.cpp
File metadata and controls
41 lines (37 loc) · 925 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*************************************************
Author: wenhaofang
Date: 2023-03-12
Description: leetcode169 - Majority Element
*************************************************/
#include <bits/stdc++.h>
using namespace std;
/**
* 方法一:
*
* 理论时间复杂度:O(n),其中 n 为数组大小
* 理论空间复杂度:O(n),其中 n 为数组大小
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> map;
int n = nums.size();
int m = n / 2;
for (int num: nums) {
map[num]++;
if (map[num] > m) {
return num;
}
}
return -1;
}
};
/**
* 测试
*/
int main() {
Solution* solution = new Solution();
vector<int> nums = {3, 2, 3};
int ans = solution -> majorityElement(nums);
cout << ans << endl;
}