题目:
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.
思路:
采用哈希表:首先扫描一遍,计算出每个数字出现的个数;然后再扫描一遍哈希表,假设当前扫描到的数字是i,那么看i + 1是否也出现在哈希表中,如果是,则hash[i] + hash[i + 1]就构成了一个harmonious subsequence。最后统计最长的harmonious subsequence的长度即可。采用哈希表的时间复杂度是O(n),空间复杂度是输入敏感的,但最坏情况下也是O(n)。
当然我们也可以首先对nums进行排序,然后再计算harnomious subsequence。这样的话,时间复杂度就是O(nlogn),但是空间复杂度却可以做到O(1)。
代码:
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> hash; // {value, appear_count}
for (auto &num : nums) {
++hash[num];
}
int ret = 0, temp = 0;
for (auto it = hash.begin(); it != hash.end(); ++it) {
if (hash.count(it->first + 1) > 0) {
temp = it->second + hash[it->first + 1];
ret = max(ret, temp);
}
}
return ret;
}
};