diff --git a/notes/剑指 offer 题解.md b/notes/剑指 offer 题解.md index 8593f936..cd0599e8 100644 --- a/notes/剑指 offer 题解.md +++ b/notes/剑指 offer 题解.md @@ -1778,47 +1778,46 @@ public int MoreThanHalfNum_Solution(int[] nums) { 找到第 K 个元素之后,就可以再遍历一次数组,所有小于等于该元素的数组元素都是最小的 K 个数。 ```java -public ArrayList GetLeastNumbers_Solution(int[] nums, int k) { - if (k > nums.length || k <= 0) - return new ArrayList<>(); - int kthSmallest = findKthSmallest(nums, k - 1); - ArrayList 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; + public ArrayList GetLeastNumbers_Solution(int[] input, int k) { + ArrayList res = new ArrayList<>(); + if (k > input.length || k <= 0) return res; + findKthSmallest(input, k - 1); + for (int i = 0; i < k; i++) { + res.add(input[i]); + } + return res; } - 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); + private void findKthSmallest(int[] nums, int k) { + int l = 0, h = nums.length - 1; + while (l < h) { + int j = paration(nums, l, h); + if (j == k) break; + else if (j > k) h = j - 1; + else l = j + 1; + } } - 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; -} + private int paration(int[] nums, int l, int h) { + //nums[l+1,i] nums[j,h] + int i = l, j = h + 1; + while (true) { + while (i < h && nums[++i] < nums[l]) ; + while (j > l + 1 && nums[--j] > nums[l]) ; + 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 的最小堆