https://leetcode.com/problems/longest-harmonious-subsequence/description/
Solution 1. Use a map
int findLHS(vector<int>& nums) {
if(nums.size()==0) return 0;
map<int,int> cnt;
for(int n : nums)
cnt[n]++;
int prevNum = 0, prevCnt = 0;
int res = 0, tmp = 0;
for(pair<int,int> p: cnt) {
if(prevCnt && p.first == prevNum+1) {
tmp = p.second + prevCnt;
res = res>tmp? res:tmp;
}
prevNum = p.first;
prevCnt = p.second;
}
return res;
}
Solution 2. Fast but tedious (beat 97%)
int findLHS(vector<int>& nums) {
if(nums.size() < 2) return 0;
sort(nums.begin(), nums.end());
int cur = nums[0], prevNum = nums[0], prevCnt = 0, cnt = 0;
int res = 0;
for(int n: nums) {
if(n == cur) {
cnt++;
continue;
}
if(prevNum + 1 == cur)
res = res>(prevCnt+cnt)? res: (prevCnt+cnt);
prevCnt = cnt;
prevNum = cur;
cur = n;
cnt = 1;
}
if(prevNum + 1 == cur)
res = res>(prevCnt+cnt)? res: (prevCnt+cnt);
return res;
}
Or simplify the code by adding an additional number at the end.
int findLHS(vector<int>& nums) {
if(nums.size() < 2) return 0;
sort(nums.begin(), nums.end());
nums.push_back(nums.back()+1);
int cur = nums[0], prevNum = nums[0], prevCnt = 0, cnt = 0, res = 0;
for(int n: nums) {
if(n == cur) {
cnt++;
continue;
}
if(prevNum + 1 == cur)
res = res>(prevCnt+cnt)? res: (prevCnt+cnt);
prevCnt = cnt;
prevNum = cur;
cur = n;
cnt = 1;
}
return res;
}
No comments:
Post a Comment