find some mistakes

This commit is contained in:
evanljp 2018-05-12 16:26:50 +08:00
parent 63c24c4c7e
commit 954fbfa468

View File

@ -1778,46 +1778,45 @@ public int MoreThanHalfNum_Solution(int[] nums) {
找到第 K 个元素之后,就可以再遍历一次数组,所有小于等于该元素的数组元素都是最小的 K 个数。 找到第 K 个元素之后,就可以再遍历一次数组,所有小于等于该元素的数组元素都是最小的 K 个数。
```java ```java
public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) { public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
if (k > nums.length || k <= 0) ArrayList<Integer> res = new ArrayList<>();
return new ArrayList<>(); if (k > input.length || k <= 0) return res;
int kthSmallest = findKthSmallest(nums, k - 1); findKthSmallest(input, k - 1);
ArrayList<Integer> ret = new ArrayList<>(); for (int i = 0; i < k; i++) {
for (int val : nums) res.add(input[i]);
if (val <= kthSmallest && ret.size() < k) }
ret.add(val); return res;
return ret;
} }
public int findKthSmallest(int[] nums, int k) { private void findKthSmallest(int[] nums, int k) {
int l = 0, h = nums.length - 1; int l = 0, h = nums.length - 1;
while (l < h) { while (l < h) {
int j = partition(nums, l, h); int j = paration(nums, l, h);
if (j == k) if (j == k) break;
break; else if (j > k) h = j - 1;
if (j > k) else l = j + 1;
h = j - 1;
else
l = j + 1;
} }
return nums[k];
} }
private int partition(int[] nums, int l, int h) { private int paration(int[] nums, int l, int h) {
//nums[l+1,i] nums[j,h]
int i = l, j = h + 1; int i = l, j = h + 1;
while (true) { while (true) {
while (i < h && nums[++i] < nums[l]) ; while (i < h && nums[++i] < nums[l]) ;
while (j > l && nums[l] < nums[--j]) ; while (j > l + 1 && nums[--j] > nums[l]) ;
if (i >= j) if (i >= j) break;
break;
swap(nums, i, j); swap(nums, i, j);
} }
swap(nums, l, j); swap(nums, l, j);
return j; return j;
} }
private void swap(int[] nums, int i, int j) { private void swap(int[] nums, int i, int j) {
int t = nums[i]; nums[i] = nums[j]; nums[j] = t; int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
} }
``` ```