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.
Solution
- 统计每个数字出现的个数,生成 num——count 的字典
- 遍历字典,判断 num + 1 的键是否存在字典中,存在则对比之前的最大长度,取最大值(default=0)
Python
1 | class Solution(object): |
使用 Counter
1 | def findLHS(self, A): |