594. 最长和谐子序列(javascript)594. Longest Harmonious Subsequence

和谐数组是指一个数组里元素的最大值和最小值之间的差别 正好是 1 。

现在,给你一个整数数组 nums ,请你在所有可能的子序列中找到最长的和谐子序列的长度。

数组的子序列是一个由数组派生出来的序列,它可以通过删除一些元素或不删除元素、且不改变其余元素的顺序而得到。

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 = [1,3,2,2,5,2,3,7]
输出:5
解释:最长的和谐子序列是 [3,2,2,2,3]

示例 2:

输入:nums = [1,2,3,4]
输出:2

示例 3:

输入:nums = [1,1,1,1]
输出:0

提示:

1 <= nums.length <= 2 * 104
-109 <= nums[i] <= 109

解题思路:

  1. 找到最长的和谐子序列的长度。,所以可以给数组进行正序排列
  2. 采用双指针,对数组进行循环遍历
  3. 当发现两个指针指向的数字差值为1,保留两个指针的下标之差+1
  4. nums[i] - nums[start] > 1时,start指针向右移动直到跳出循环
/**
 * @param {number[]} nums
 * @return {number}
 */
var findLHS = function (nums) {
    nums.sort((a, b) => a - b)
    let start = 0
    let getMax = 0
    for (let i = 0; i < nums.length; i++) {
        while (nums[i] - nums[start] > 1) {
            start++
        }
        if (nums[i] - nums[start] === 1) {
            getMax = Math.max(getMax, i - start + 1)
        }
    }
    return getMax
};

leetcode : https://leetcode.cn/problems/longest-harmonious-subsequence/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值