最小的K个数-40
输入n个整数,找出其中最小的k个数。
注意:
- 数据保证k一定小于等于输入数组的长度;
- 输出数组内元素请按从小到大顺序排序;
样例
输入:[1,2,3,4,5,6,7,8] , k=4
输出:[1,2,3,4]
思路:
partition
class Solution {
public List<Integer> getLeastNumbers(int[] nums, int k) {
List<Integer> res = new ArrayList<>();
int left = 0, right = nums.length - 1;
int mid = left + (right - left) / 2;
int index = partition(nums, left, right);
while (index != k - 1) {
if (index > mid) index = partition(nums, left, index - 1);
else if (index < mid) index = partition(nums, index + 1, right);
}
for (int i = 0; i < index; i++) res.add(nums[i]);
return res;
}
private int partition(int[] nums, int left, int right) {
int temp = nums[left];
while (left < right) {
while (left < right && nums[right] >= temp) right--;
nums[left] = nums[right];
while (left < right && nums[left] <= temp) left++;
nums[right] = nums[left];
}
nums[left] = temp;
return left;
}
}
小根堆
class Solution {
public List<Integer> getLeastNumbers_Solution(int [] input, int k) {
List<Integer> res = new ArrayList<>();
PriorityQueue<Integer> maxpq = new PriorityQueue<>();
for(int num : input){
maxpq.add(num);
}
for(int i = 0; i < k; i++){
res.add(maxpq.poll());
}
return res;
}
}
堆排序要复习一下了…