leetcode 594. Longest Harmonious Subsequence

本文介绍了一种寻找整数数组中最长和谐子序列的方法。和谐数组定义为最大值与最小值之差恰好为1的数组。通过排序或使用哈希映射的方法,文章详细解释了如何高效地找到这样的子序列及其长度。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

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


开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值