594. Longest Harmonious Subsequence
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Example 2:
Input: nums = [1,2,3,4]
Output: 2
Example 3:
Input: nums = [1,1,1,1]
Output: 0
Constraints:
1 <= nums.length <= 2 * 104
-109 <= nums[i] <= 109
solution1 enumeration
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> cnt;
int res = 0;
for (int num : nums) {
cnt[num]++;
}
for (auto [key, val] : cnt) {
if (cnt.count(key + 1)) {
res = max(res, val + cnt[key + 1]);
}
}
return res;
}
};
solution2 hash table
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> cnt;
int res = 0;
for (int num : nums) {
cnt[num]++;
}
for (auto [key, val] : cnt) {
if (cnt.count(key + 1)) {
res = max(res, val + cnt[key + 1]);
}
}
return res;
}
};
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/longest-harmonious-subsequence/solution/zui-chang-he-xie-zi-xu-lie-by-leetcode-s-8cyr/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
class Solution {
public:
int findLHS(vector<int>& nums) {
sort(nums.begin(),nums.end());
unordered_map<int,int>map;
for(auto x:nums){
++map[x];
}
int ans=0,temp=0;
for(int i=1;i<nums.size();i++){
if((nums[i]-nums[i-1])==1){
temp=map[nums[i]]+map[nums[i-1]];
}
if(temp>ans){
ans=temp;
}
}
return ans;
}
};