public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
if (k > nums.length || k <= 0) return new ArrayList<>();
int kthSmallest = findKthSmallest(nums, k - 1);
ArrayList<Integer> ret = new ArrayList<>();
for (int val : nums) {
if (val <= kthSmallest && ret.size() < k) {
ret.add(val);
}
}
return ret;
}
public int findKthSmallest(int[] nums, int k) {
int l = 0, h = nums.length - 1;
while (l < h) {
int j = partition(nums, l, h);
if (j == k) break;
if (j > k) h = j - 1;
else l = j + 1;
}
return nums[k];
}
private int partition(int[] nums, int l, int h) {
int i = l, j = h + 1;
while (true) {
while (i < h && nums[++i] < nums[l]) ;
while (j > l && nums[l] < nums[--j]) ;
if (i >= j) break;
swap(nums, i, j);
}
swap(nums, l, j);
return j;
}
private void swap(int[] nums, int i, int j) {
int t = nums[i]; nums[i] = nums[j]; nums[j] = t;
}
最小的k个数(快速排序)
最新推荐文章于 2022-07-22 11:15:33 发布