JZ29 最小的K个数
https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&&tqId=11182&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
import java.util.ArrayList;
import java.util.Arrays;
public class GetLeastNumbers {
public static void main(String[] args) {
int[] input = {4,5,1,6,2,7,3,8};
int k = 4;
new GetLeastNumbers().GetLeastNumbers_Solution(input,k).forEach(tmp->{
System.out.println(tmp);
});
}
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
ArrayList<Integer> res = new ArrayList<>();
if(k==0){
return res;
}
// Arrays.sort(input);
quickSort(input,0,input.length-1);
for(int i=0;i<k;i++){
res.add(input[i]);
}
return res;
}
//快速排序
public void quickSort(int[] input,int l,int r){
if(l<r){
int key = input[l];
int i = l;
int j = r;
while(i<j){
while(i<j&&input[j]>=key){
j--;
}
if(i<j){
input[i] = input[j];
i++;
}
while(i<j&&input[i]<key){
i++;
}
if(i<j){
input[j] = input[i];
j--;
}
}
input[i] = key;
quickSort(input,l,i-1);
quickSort(input,i+1,r);
}
}
}
JZ63 数据流中的中位数
->https://www.nowcoder.com/practice/9be0172896bd43948f8a32fb954e1be1?tpId=13&&tqId=11216&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
/*
使用大小顶堆
小顶堆队首为队列中最小的值,大顶堆相反
因此我们可以在大顶堆中存放全部数字的前半部分,小顶堆中存放数组的后半部分
*/
private int count = 0;//全部数字的数量
private PriorityQueue<Integer> low = new PriorityQueue<>();//默认小顶堆
private PriorityQueue<Integer> high = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1); //return (02 < o1) ? -1 : ((o2 == o1) ? 0 : 1);
}
});
public void Insert(Integer num) {
count++;
if((count&1)==1){//如果是奇数,我们在取中位数时候只需要取出大顶堆的堆顶元素,但是要防止num会比小顶堆中的数小
if(!low.isEmpty()&&num>low.peek()){
low.offer(num);
num = low.poll();
}
high.offer(num);
}else{
if(!high.isEmpty()&&num<high.peek()){
high.offer(num);
num = high.poll();
}
low.offer(num);
}
}
public Double GetMedian() {
double res = 0;
if((count&1)==1){
res = high.peek();
}else{
res = (high.peek()+low.peek())/2.0;
}
return res;
}
}