-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestHarmoniousSubsequence.cpp
More file actions
59 lines (58 loc) · 1.35 KB
/
Copy pathlongestHarmoniousSubsequence.cpp
File metadata and controls
59 lines (58 loc) · 1.35 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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
//O(n)
int findLHS(vector<int> &nums)
{
unordered_map<int, int> hashMap;
for (int i : nums)
hashMap[i]++;
int res = 0;
for (int i : nums)
{
if (hashMap.find(i + 1) != hashMap.end())
res = max(res, hashMap[i + 1]);
if (hashMap.find(i - 1) != hashMap.end())
res = max(res, hashMap[i - 1]);
}
return res;
}
//O(nlogn)
int findLHS(vector<int> &nums)
{
sort(nums.begin(), nums.end());
int prev_cnt = 0, res = 0;
for (int i = 0; i < nums.size(); ++i)
{
int cnt = 1;
if (i > 0 && nums[i] - nums[i - 1] == 1)
{
while (i < nums.size() - 1 && nums[i] == nums[i + 1])
{
cnt++;
i++;
}
res = max(res, cnt + prev_cnt);
prev_cnt = cnt;
}
else
{
while (i < nums.size() - 1 && nums[i] == nums[i + 1])
{
cnt++;
i++;
}
prev_cnt = cnt;
}
}
return res;
}
};
int main()
{
int n;
cin >> n;
vector<int> nums(n);
}