0594. Longest Harmonious Subsequence (E)
Longest Harmonious Subsequence (E)
题目
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 * 10^4
-10^9 <= nums[i] <= 10^9
题意
在给定数组中找到一个子数组,使其中的最大值和最小值的差正好为1。
思路
根据题意,这样的子数组中只可能存在两种不同的数,有以下两种方法:
先将数组排序,再利用滑动窗口找到首尾差为1的子数组,复杂度为\(O(N)\)。
或可以用HashMap记录每个数字的出现次数,在遍历时,当前数为num,判断num-1和num+1是否存在,存在的话则比较max(ans, num出现次数 + (num-1) or (num+1)出现次数)。
代码实现
Java
排序
class Solution {
public int findLHS(int[] nums) {
if (nums.length == 1) {
return 0;
}
int ans = 0;
int left = 0, right = 1;
Arrays.sort(nums);
while (left <= nums.length - 2) {
if (nums[right] - nums[left] == 1) {
ans = Math.max(ans, right - left + 1);
right++;
} else if (nums[right] - nums[left] > 1) {
left++;
} else {
right++;
}
if (left == right) right++;
if (right == nums.length) break;
}
return ans;
}
}
Hash
class Solution {
public int findLHS(int[] nums) {
int ans = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
int cnt = map.getOrDefault(num, 0) + 1;
if (map.containsKey(num - 1)) {
ans = Math.max(ans, map.get(num - 1) + cnt);
}
if (map.containsKey(num + 1)) {
ans = Math.max(ans, map.get(num + 1) + cnt);
}
map.put(num, cnt);
}
return ans;
}
}