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.
和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1 。
现在,给你一个整数数组 nums ,请你在所有可能的子序列中找到最长的和谐子序列的长度。
数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-harmonious-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。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来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-harmonious-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
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));
}
}