[JavaScript 刷题] 数组 - 划分数组使最大差为 K,leetcode 2294
Posted GoldenaArcher
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JavaScript 刷题] 数组 - 划分数组使最大差为 K,leetcode 2294相关的知识,希望对你有一定的参考价值。
[javascript 刷题] 数组 - 划分数组使最大差为 K,leetcode 2294
github repo 地址: https://github.com/GoldenaArcher/js_leetcode,Github 的目录 大概 会更新的更勤快一些。
题目地址:2294. Partition Array Such That Maximum Difference Is K
题目
如下:
You are given an integer array
nums
and an integerk
. You may partition nums into one or more subsequences such that each element innums
appears in exactly one of the subsequences.Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most
k
.A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
解题思路
基本上说看到这种题,包括最大最小值,第一个考虑的就是排序。
以这道题的例子来说:
nums = [3,6,1,2,5], k = 2
We can partition nums into the two subsequences
[3,1,2]
and[6,5]
.
对于这道题的 subsequence 来说,顺序就不是这么的重要了,如果将这个数组进行排序之后就能很方便的解决这道题。
[3,6,1,2,5]
进行排序后就能获得 [1,2,3,5,6]
,这时候只要保存一个变量作为当前 subsequence 中的最小值,随后遍历到 nums[i + n] - nums[i] > k
的点再重复该步骤即可。
使用 JavaScript 解题
/**
* @param number[] nums
* @param number k
* @return number
*/
var partitionArray = function (nums, k)
nums.sort((a, b) => a - b);
let counter = 0;
for (let i = 0; i < nums.length; i++)
const curr = nums[i];
while (nums[i] - curr <= k)
i++;
i--;
counter++;
return counter;
;
开发者涨薪指南
48位大咖的思考法则、工作方式、逻辑体系
以上是关于[JavaScript 刷题] 数组 - 划分数组使最大差为 K,leetcode 2294的主要内容,如果未能解决你的问题,请参考以下文章
[JavaScript 刷题] 数组 - 替换数组中的元素,leetcode 2295
[JavaScript 刷题] Code Signal - 改变数组(arrayChange)
[JavaScript 刷题] Code Signal - 相似数组(Are Similar?)
[JavaScript 刷题] 哈希表 - 两个数组的交集 II,leetcode 350