如何在 QuickSelect 中实现重复

How to implement duplicates in QuickSelect

我做了一个快速的select算法,就是找一个数组中第k小的数。我的问题是,它只适用于没有重复的数组。 如果我有一个数组

arr = {1,2,2,3,5,5,8,2,4,8,8}

上面会说第三小的数是2,其实是3

我不知道该怎么做,这是我的两种方法 quickSelect 和 Partition:

private int quickselect(int[] array, int leftIndex, int rightIndex, int kthSmallest) {

    if(kthSmallest > array.length - 1){
        System.out.print("Number does not exist. Please enter a number less than: ");
        return array.length - 1;
    }

    if (leftIndex == rightIndex) {
        return array[leftIndex];
    }

    int indexOfPivot = generatePivot(leftIndex, rightIndex);

    indexOfPivot = quickSelectPartition(array, leftIndex, rightIndex, indexOfPivot);

    if (kthSmallest == indexOfPivot) {

        return array[kthSmallest];

    } else if (kthSmallest < indexOfPivot) {

        return quickselect(array, leftIndex, indexOfPivot - 1, kthSmallest);

    } else {

        return quickselect(array, indexOfPivot + 1, rightIndex, kthSmallest);
    }
}


private int quickSelectPartition(int[] array, int left, int right, int pivotIndex) {

    int pivotValue = array[pivotIndex];

    swapIndexes(array, pivotIndex, right);

    int firstPointer = left;

    for(int secondPointer = left; secondPointer < right; secondPointer++) {

        if(array[secondPointer] < pivotValue) {

            swapIndexes(array, firstPointer, secondPointer);

            firstPointer++;
        }
    }

    swapIndexes(array, right, firstPointer);

    return firstPointer;
}

如果可以接受将 2xN 添加到 运行 时间,您可以先将不同的元素复制到一个新数组中:

private int[] getDistinct(int[] array) {
    Set<Integer> distinct = new HashSet<>();
    int endIdx = 0;

    for (int element : array) {

        if (distinct.add(element)) {
            array[endIdx++] = element;
        }
    }

    return Arrays.copyOfRange(array, 0, endIdx);
}

然后对其进行快速选择:

int[] arr = new int[] {1, 2, 2, 3, 5, 5, 8, 2, 4, 8, 8};
int kthSmallest = 6;

int[] distinctArray = getDistinct(arr);
int kthSmallestElement = quickselect(distinctArray, 0, distinctArray.length - 1, kthSmallest - 1);

System.out.println(kthSmallestElement);

输出:

8