最小的k个数
来源:互联网 发布:淘宝卖家的卡片祝福语 编辑:程序博客网 时间:2024/06/15 16:35
//法一:基于快排partition函数,时间复杂度为O(n)
public class SmallerKnumber {
public static void main(String[] args) {
int[]a={2,4,5,46,32,42,7};
int k=5;
int start=0,end=a.length-1;
int index=partition(a,start,end);
while(index!=k-1){
if(index>k-1){
end=index-1;
index=partition(a,start,end);
}else{
start=index+1;
index=partition(a,start,end);
}
}
for(int i=0;i<k;i++){
System.out.print(a[i]+" ");
}
}
public static int partition(int[]a,int start,int end){
int i=start,j=end;
int x=a[start];
while(i<j){
while(i<j&&a[j]>=x)j--;
a[i]=a[j];
while(i<j&&a[i]<=x)i++;
a[j]=a[i];
}
a[i]=x;
return i;
}
}
//法二:
package 数组;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class SmallerKnumber {
public static void main(String[] args) {
int[]a={2,4,5,46,32,42,7};
int k=5;
ArrayList<Integer> array=GetLeastNumbers_Solution(a,k);
for(int i=0;i<array.size();i++){//遍历ArrayList数组
System.out.print(array.get(i)+" ");
}
}
public static ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
ArrayList<Integer> result = new ArrayList<Integer>();//返回的数组
int length = input.length;
if(k > length || k == 0){
return result;
}
PriorityQueue<Integer> maxHeap = new //PriorityQueue为大根堆
PriorityQueue<Integer>(k, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {//排序规则
return o2.compareTo(o1);
}
});
for (int i=0;i<length;i++) {
if (maxHeap.size()<k) {
maxHeap.offer(input[i]);
} else if (maxHeap.peek() > input[i]) {
Integer temp = maxHeap.poll();
temp = null;
maxHeap.offer(input[i]);
}else{}
}
for (Integer integer : maxHeap) {
result.add(integer);
}
return result;
}
}
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的k个数
- 最小的K个数
- 最小的k个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的K个数
- 最小的k个数
- 最小的k个数
- C语言实现通讯录-动态内存
- 用于目标检测的rcnn,fast-rcnn,faster-rcnn
- 姿态论文整理--04-Human pose estimation using global and local normalization
- 渗透入门学习之http数据包
- B OOXX Game(FZU 2151)
- 最小的k个数
- HttpWebRequest的GetResponse或GetRequestStream偶尔超时 + 总结各种超时死掉的可能和相应的解决办法
- LeetCode.402 Remove K Digits
- 笔试题3
- Java8中对HashMap的改造
- POJ
- Tomcat类加载机制触发的Too many open files问题分析
- 字节输入输出流
- linux 中的DNS服务