《中英双解》leetcode Longest Harmonious Subsequence(最长和谐子序列)

该博客探讨了如何解决LeetCode上的‘最长和谐子序列’问题。提供了两种解决方案,一种是使用排序和迭代,另一种是利用哈希表。示例代码分别展示了这两种方法,能够找出给定数组中最长的和谐子序列的长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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));
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值