auto commit

This commit is contained in:
CyC2018 2018-05-12 21:22:36 +08:00
parent bd8b6bfb14
commit dbf64f2e02

View File

@ -1779,46 +1779,49 @@ public int MoreThanHalfNum_Solution(int[] nums) {
找到第 K 个元素之后,就可以再遍历一次数组,所有小于等于该元素的数组元素都是最小的 K 个数。 找到第 K 个元素之后,就可以再遍历一次数组,所有小于等于该元素的数组元素都是最小的 K 个数。
```java ```java
public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
ArrayList<Integer> res = new ArrayList<>(); ArrayList<Integer> ret = new ArrayList<>();
if (k > input.length || k <= 0) return res; if (k > nums.length || k <= 0)
findKthSmallest(input, k - 1); return ret;
for (int i = 0; i < k; i++) { int kthSmallest = findKthSmallest(nums, k - 1);
res.add(input[i]); // findKthSmallest 会让改变数组,使得前 k 个数都是最小的 k 个数
} for (int i = 0; i < k; i++)
return res; ret.add(nums[i]);
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 void findKthSmallest(int[] nums, int k) { private int partition(int[] nums, int l, int h) {
int l = 0, h = nums.length - 1; int i = l, j = h + 1;
while (l < h) { while (true) {
int j = paration(nums, l, h); while (i < h && nums[++i] < nums[l]) ;
if (j == k) break; while (j > l && nums[l] < nums[--j]) ;
else if (j > k) h = j - 1; if (i >= j)
else l = j + 1; break;
} swap(nums, i, j);
} }
swap(nums, l, j);
return j;
}
private int paration(int[] nums, int l, int h) { private void swap(int[] nums, int i, int j) {
//nums[l+1,i] nums[j,h] int t = nums[i];
int i = l, j = h + 1; nums[i] = nums[j];
while (true) { nums[j] = t;
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 的最小堆 ### 大小为 K 的最小堆