题解 | #第k轻的牛牛#
第k轻的牛牛
https://www.nowcoder.com/practice/7676478b46794456b145e8e48b0e2763
知识点:快速排序
对于时间复杂度为 O(n) 的方法,我们需要使用快速排序的思想。
随机选择一个枢轴index,利用快速排序的方法,将大于该weights[index]的值移动到index右边,小于weights[index]的值移动到index左边,这样就做到了index位置的值一定是第index-1小的值。若index大于k-1,则说明第k小的值在左边,只需要递归左侧子数组即可,同理,若index小于k-1,说明第k小的值在右边,则递归右侧子数组。这样只需要遍历一半的空间,提高了时间效率。
Java题解如下:
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param weights int整型一维数组 * @param k int整型 * @return int整型 */ public int findKthSmallest (int[] weights, int k) { // write code here return quickSelect(weights, 0, weights.length - 1, k); } private int quickSelect(int[] weights, int left, int right, int k) { Random random = new Random(); int index = left + random.nextInt(right - left + 1); int target = weights[index]; int i = left, j = right; weights[index] = weights[j]; while(i < j) { while(i < j && weights[i] <= target) { i++; } weights[j] = weights[i]; while(i < j && weights[j] >= target) { j--; } weights[i] = weights[j]; } weights[j] = target; if(i == k - 1) { return weights[i]; }else if(i > k - 1) { return quickSelect(weights, left, i - 1, k); }else { return quickSelect(weights, i + 1, right, k); } } }