简体   繁体   English

在网格中找到第 K 个最小元素?

[英]Find the Kth min element in the grid?

We are given a grid of size N * N where each element A[i][j] is calculated by this equation (i + j) ^ 2 + (ji) * 10^5 .我们给定一个大小为N * N网格,其中每个元素A[i][j]由这个等式(i + j) ^ 2 + (ji) * 10^5计算。

We need to find the Kth min element in optimized way.我们需要以优化的方式找到第K 个最小元素

Constraints :约束

1 <= number of test cases <= 20 
1 <= N <= 5*10^4 
1 <= k <= N^2

How to solve this problem in an efficient way?如何有效地解决这个问题?

The problem that you are trying to solve (finding kth smallest element in an unordered array) is called the selection problem .您尝试解决的问题(在无序数组中查找第 k 个最小元素)称为选择问题 There are many ways to solve this problem, and one of the best known ways is the quick select algorithm .有很多方法可以解决这个问题,其中最著名的方法之一是快速 select 算法

You can solve this problem in O(N log N) time.您可以在 O(N log N) 时间内解决此问题。 Note that that is sublinear in the size of the matrix, which is N*N.请注意,这在矩阵的大小上是次线性的,即 N*N。 Of course you should never actually construct the matrix.当然,您永远不应该实际构建矩阵。

First, it helps to see what the values in the matrix looks like :首先,它有助于查看矩阵中的值是什么的:

Note that over the possible range of matrix sizes, the smallest element is always at (i,j) = (N-1,0).请注意,在矩阵大小的可能范围内,最小元素始终位于 (i,j) = (N-1,0)。

The largest element will be either (0,N-1) or (N-1,N-1), depending on the size of the matrix.最大元素将是 (0,N-1) 或 (N-1,N-1),具体取决于矩阵的大小。

Consider the elements on the line from the smallest to largest.从最小到最大考虑线上的元素。 If you pick any one of these elements, then you can trace the contour to find the number of <= elements in O(N) time.如果您选择其中任何一个元素,则可以跟踪轮廓以在 O(N) 时间内找到 <= 元素的数量。

Furthermore, the elements on this line are always monotonically increasing from smallest to largest, so do a binary search on this line of elements, to find the largest one such that the number of <= elements is < k.此外,这一行的元素总是从最小到最大单调递增,所以对这一行元素进行二分搜索,找到最大的一个,使得 <= 元素的数量为 < k。 At O(N) time per test, this takes O(N log N) all together.在每个测试的 O(N) 时间,这需要 O(N log N) 一起。

Let's say the element you discover has value x, and the number of elements <= x is r, with r < k.假设您发现的元素具有值 x,并且元素的数量 <= x 是 r,其中 r < k。 Next trace the contour for the next higher element on the line, call its value y, and make list of all the values v such that x < v <= y.接下来跟踪该线上下一个更高元素的轮廓,调用它的值 y,并列出所有值 v 使得 x < v <= y。 There will be O(N) elements in this list, and this takes only O(N) time.此列表中将有 O(N) 个元素,这仅需要 O(N) 时间。

Finally, just use sorting or quickselect to pick the (kr)th element from this list.最后,只需使用排序或快速选择从该列表中选择第 (kr) 个元素。 Again this takes at mostO(N log N) time.同样,这最多需要 O(N log N) 时间。

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

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