594.最长融洽子序列(javascript)594.LongestHarmoniousSubsequence
原创和谐数组是指数组中元素的最大值和最小值之间的差异。 正好是 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,保持两个指针的下标之间的差异+1
-
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/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123




