We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Note: The length of the input array will not exceed 20,000.
因为它只要求子序列的长度,想法就是先排序,然后遍历数组,对前一个数字的子序列与当前数字的子序列进行判断比较
public class Solution {
public int findLHS(int[] nums) {
int len = nums.length;
if(len<=0) return 0;
Arrays.sort(nums);
int pre=nums[0], preCnt=0, singleCnt=1, max=0;
for(int i=1; i<len; i++){
if(nums[i]==pre){
singleCnt++;
}else if(nums[i]-pre==1){
pre = nums[i];
preCnt = singleCnt;
singleCnt = 1;
}else{
pre = nums[i];
preCnt = 0;
singleCnt = 1;
}
if(preCnt!=0 && preCnt+singleCnt>max){
max = preCnt+singleCnt;
}
}
return max;
}
}
也可以使用hashmap来做
public int findLHS(int[] nums) {
Map<Long, Integer> map = new HashMap<>();
for (long num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
int result = 0;
for (long key : map.keySet()) {
if (map.containsKey(key + 1)) {
result = Math.max(result, map.get(key + 1) + map.get(key));
}
}
return result;
}
本文介绍了一种寻找整数数组中最长和谐子序列的方法。和谐数组定义为最大值与最小值之差恰好为1的数组。通过排序或使用哈希映射的方法,文章详细解释了如何高效地找到这样的子序列及其长度。
5112

被折叠的 条评论
为什么被折叠?



