We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Note: The length of the input array will not exceed 20,000.
思路1
int findLHS(vector<int>& nums) {
unordered_map<int, int> res;
for (auto x : nums)res[x]++;
int maxlen = 0;
for (auto it : res){
if (res.count(it.first + 1)){
maxlen = max(maxlen, it.second + res[it.first + 1]);
}
}
return maxlen;
}
算法的时间复杂度为O(n),空间复杂度为O(n)。
思路2
int findLHS(vector<int>& nums) {
sort(nums.begin(), nums.end());
int low = 0, high = 0, maxlen = 0;
while (low < high && high < nums.size()){
if (nums[high] - nums[low] == 1){
maxlen = max(maxlen, high - low + 1);
high++;
}
else if (nums[high] - nums[low] < 1){
high++;
}
else low++;
}
return maxlen;
}
此算法的时间复杂度为O(nlog(n)),空间复杂度为O(1)。