LeetCode 594. Longest Harmonious Subsequence
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:
1 | Input: [1,3,2,2,5,2,3,7] |
Note: The length of the input array will not exceed 20,000.
这道题要注意两点:
- 是子串而不是连续子串
- 是exactly one而不是less than one
因为不要求连续,所以实际上找到两个连续的数,把他们的出现次数加起来就是要找的子串长度了。每个整数出现了多少次用哈希表来保存。
1 | class Solution { |