leetcode-594-easy
Longest Harmonious Subsequence
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Example 2:
Input: nums = [1,2,3,4]
Output: 2
Example 3:
Input: nums = [1,1,1,1]
Output: 0
Constraints:
1 <= nums.length <= 2 * 104
-109 <= nums[i] <= 109
思路一:用 map 统计数组中数字重复出现次数,最后只要遍历数组,查找对应的数字 num 和相邻的数字 num+1 出现的次数。题目中数组中数字出现的顺序是障眼法,不用管
public int findLHS(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.compute(num, (k, v) -> v == null ? 1 : v + 1);
}
int max = 0;
for (int num : nums) {
if (map.containsKey(num) && map.containsKey(num + 1)) {
max = Math.max(max, map.get(num) + map.get(num + 1));
}
}
return max;
}

浙公网安备 33010602011771号