-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathn-repeated.cpp
More file actions
64 lines (54 loc) · 1.3 KB
/
n-repeated.cpp
File metadata and controls
64 lines (54 loc) · 1.3 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <vector>
#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
// 80ms slow O(n)
// class Solution {
// public:
// int repeatedNTimes(vector<int>& A) {
// unordered_map<int, int> umap;
// int max = 0;
// int val = 0;
// int nMax = A.size() / 2;
// for (int i = 0; i < A.size(); i++)
// {
// if(!umap[A[i]]) {
// umap[A[i]] = 1;
// } else {
// umap[A[i]]++;
// }
// if(umap[A[i]] > max && umap[A[i]] <= nMax){
// max = umap[A[i]];
// val = A[i];
// }
// }
// return val;
// }
// };
class Solution {
public:
int repeatedNTimes(vector<int>& A) {
sort(A.begin(), A.end());
if(A[(A.size() - 1) / 2] == A[(A.size() - 1) / 2 - 1]) {
return A[A.size() / 2 - 1];
} else if (A[A.size() / 2] == A[A.size() / 2 + 1]){
return A[A.size() / 2 + 1];
}
return 0;
}
void print_array(vector<int> vec){
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << ", ";
}
cout << endl;
}
};
int main(){
vector<int> i = {9,5,3,3};
Solution s;
int res = s.repeatedNTimes(i);
cout << res << endl;
return 0;
}