原题链接在这里:https://leetcode.com/problems/longest-harmonious-subsequence/description/
题目:
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.
题解:
在HashMap<Integer, Integer> hm中计数nums中每个element出现次数.
再看hm的key加一是否也在hm中能找到, 若能计算个数sum更新res.
Time Complexity: O(n). Space: O(n).
AC Java:
class Solution {
public int findLHS(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
} int res = 0;
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
for(int n : nums){
hm.put(n, hm.getOrDefault(n, 0)+1);
} for(int i : hm.keySet()){
if(hm.containsKey(i+1)){
res = Math.max(res, hm.get(i)+hm.get(i+1));
}
}
return res;
}
}