package Sort;
import java.util.Arrays;
import java.util.HashMap;
public class LongestHarmoniousSubsequence {
// 和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1 。
//
// 现在,给你一个整数数组 nums ,请你在所有可能的子序列中找到最长的和谐子序列的长度。
//
// 数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到
//采用迭代的方式
public static int findLHS(int[] nums){
Arrays.sort(nums);
int begin = 0;
int res = 0;
for(int end = 0;end < nums.length;end ++){
while(nums[end] - nums[begin] > 1){
begin++;
}
if(nums[end] - nums[begin] == 1){
res = Math.max(res,end - begin + 1);
}
}
return res;
}
//采用哈希表
public static int findLHS2(int[] nums){
HashMap<Integer,Integer> hashMap = new HashMap<>();
int res = 0;
for(int num : nums){
hashMap.put(num,hashMap.getOrDefault(num,0) + 1);
}
//得到set集合
for(int key : hashMap.keySet()){
if(hashMap.containsKey(key + 1)){
res = Math.max(res,hashMap.get(key) + hashMap.get(key + 1));
}
}
return res;
}
public static void main(String[] args) {
int[] nums = new int[]{1,3,2,2,5,3,7};
System.out.println(findLHS(nums));
System.out.println(findLHS2(nums));
}
}