-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindLHS.cpp
More file actions
34 lines (33 loc) · 810 Bytes
/
findLHS.cpp
File metadata and controls
34 lines (33 loc) · 810 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
// sort
class Solution {
public:
int findLHS(vector<int>& nums) {
sort(nums.begin(),nums.end());
int begin = 0;
int res = 0;
for (int end = 0; end < nums.size(); end++) {
while (nums[end] - nums[begin] > 1) {
begin++;
}
if (nums[end] - nums[begin] == 1) {
res = max(res, end - begin + 1);
}
}
return res;
}
};
// Hash
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> m;
for (int e: nums) m[e]++;
int ans = 0;
for (auto &it: m) {
int val = it.first;
if (m.find(val + 1) != m.end())
ans = std::max(ans, it.second + m[val + 1]);
}
return ans;
}
};