1. 题目

2. 思路
(1) HashMap
- 统计所有数字出现的次数,遍历所有和谐子序列的长度即可。
(2) 滑动窗口
- 先将数组进行排序,然后利用双指针法遍历数组,若左右指针指向的元素之差等于1,则更新最长的和谐子序列的长度。
(3) 滑动窗口优化
- 与(2)不同的是,右指针不是移动到当前数字的末尾时才统计长度,而是每次移动都统计长度。
3. 代码
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int findLHS(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int res = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int next = entry.getKey() + 1;
if (map.containsKey(next)) {
res = Math.max(res, entry.getValue() + map.get(next));
}
}
return res;
}
}
class Solution1 {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int left = 0;
int mid = 0;
int right = 0;
int res = 0;
while (left < nums.length) {
while (right < nums.length && nums[right] == nums[left]) {
right++;
}
if (right == nums.length) {
return res;
}
mid = right;
if (nums[right] == nums[left] + 1) {
int num = nums[right];
while (right < nums.length && nums[right] == num) {
right++;
}
res = Math.max(res, right - left);
}
left = mid;
}
return res;
}
}
class Solution2 {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int left = 0;
int right = 0;
int res = 0;
while (right < nums.length) {
while (nums[right] - nums[left] > 1) {
left++;
}
if (nums[right] - nums[left] == 1) {
res = Math.max(res, right - left + 1);
}
right++;
}
return res;
}
}