简体   繁体   English

找到k个彼此之间差异最小的数组元素

[英]Find k number of array elements having the minimum difference amongst themselves

So basically I have an array of n integers (positive only).所以基本上我有一个n整数数组(仅正数)。 I want to have k number of integers from this array into a separate array (k<n) such that the difference between these k numbers is the minimum amongst every other k pairs of integers in an array.我想将这个数组中的k个整数放入一个单独的数组(k<n)中,这样这些 k 个数字之间的差异是数组中所有其他k对整数中的最小值。

If k is 1, I just need to return the max integer of the array.如果 k 为 1,我只需要返回数组的最大 integer。

I want to implement this in JavaScript.我想在 JavaScript 中实现这个。 I understand how to run this problem for the values k=1 and k=2 .我了解如何为值k=1k=2运行此问题。 But I don't grasp the general concept of this problem.但我没有掌握这个问题的一般概念。

For eg:例如:

Array = [6,22,21,63,99,77]

I sorted this array in ascending order.我按升序对这个数组进行了排序。 After this I don't understand how to proceed further.在此之后,我不明白如何进一步进行。

After sorting the array it becomes similar to a sliding window problem.对数组进行排序后,它变得类似于滑动 window 问题。

Run a loop from i=0 to nk and check the following.运行从i=0nk的循环并检查以下内容。

Find the minimum difference between arr[i+k] and arr[i] .找到arr[i+k]arr[i]之间的最小差异。 The index at which this occurs is your subset of k integers you want.发生这种情况的索引是您想要的k个整数的子集。 You can check this link for more details and coding help.您可以查看此 链接以获取更多详细信息和编码帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM