1 回答

TA貢獻1780條經(jīng)驗 獲得超1個贊
如果增加2×N運行時間是可以接受的,您可以首先將不同的元素復制到一個新數(shù)組中:
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
添加回答
舉報