【问题标题】:Finding index of kth smallest element in an array efficiently (iterative)?有效地(迭代)查找数组中第 k 个最小元素的索引?
【发布时间】:2023-03-11 16:40:02
【问题描述】:

我想找到数组中第 k 个最小的元素,但实际上我的分区方法需要它的索引。

我在此博客上找到了用于查找第 k 个最小元素的代码: http://blog.teamleadnet.com/2012/07/quick-select-algorithm-find-kth-element.html

但这只会返回值,而不是索引。

您知道如何有效地找到它的索引吗?

【问题讨论】:

  • 如何在大小为 k 的堆中维护数字?
  • 如果您可以将您的值存储在 TreeSet 中,您将获得非常有效的操作,而且工作量很少。
  • 如果你的数组是[a_1, a_2, ..., a_n],你可以在扩充数组[(a_1, 1), (a_2, 2), ..., (a_n, n)]上运行QuickSelect

标签: java algorithm median


【解决方案1】:

最简单的方法是创建一个额外的相同长度的indices 数组,用从0length-1 的数字填充它,当arr 数组更改时,使用indices 执行相同的更改大批。最后从indices 数组中返回对应的条目。您甚至不必了解原始算法即可执行此操作。下面是修改后的方法(我的改动标有***):

public static int selectKthIndex(int[] arr, int k) {
    if (arr == null || arr.length <= k)
        throw new IllegalArgumentException();

    int from = 0, to = arr.length - 1;

    // ***ADDED: create and fill indices array
    int[] indices = new int[arr.length];
    for (int i = 0; i < indices.length; i++)
        indices[i] = i;

    // if from == to we reached the kth element
    while (from < to) {
        int r = from, w = to;
        int mid = arr[(r + w) / 2];

        // stop if the reader and writer meets
        while (r < w) {

            if (arr[r] >= mid) { // put the large values at the end
                int tmp = arr[w];
                arr[w] = arr[r];
                arr[r] = tmp;
                // *** ADDED: here's the only place where arr is changed
                // change indices array in the same way
                tmp = indices[w];
                indices[w] = indices[r];
                indices[r] = tmp;
                w--;
            } else { // the value is smaller than the pivot, skip
                r++;
            }
        }

        // if we stepped up (r++) we need to step one down
        if (arr[r] > mid)
            r--;

        // the r pointer is on the end of the first k elements
        if (k <= r) {
            to = r;
        } else {
            from = r + 1;
        }
    }

    // *** CHANGED: return indices[k] instead of arr[k]
    return indices[k];
}

请注意,此方法会修改原始的 arr 数组。如果您不喜欢这样,请在方法的开头添加arr = arr.clone()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-13
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2021-12-24
    • 1970-01-01
    相关资源
    最近更新 更多