目录
题目描述
解法1:排序+取值
数组排序后取前k个值,注意特殊情况的判断,比如input数组长度比k还小
比如,那就返回整个数组即可。
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
Arrays.sort(input);
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < k && i < input.length; i++) {
res.add(input[i]);
}
return res;
}
}
Arrays.sort(input);使用的是快排。
时间复杂度:O(nlogn) 空间复杂度 O(k)
解法2:大根堆
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if(input.length==0||k==0){
return new ArrayList<Integer>();
}
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>(){
public int compare(Integer o1, Integer o2){
return o2 - o1;// 大根堆
}
});
for(int i = 0; i<input.length; ++i){
int tmp = input[i];
if(pq.size()<k){
pq.add(tmp);
}else{
if(tmp < pq.peek()){// pq不可能为空 不需要 !pq.isEmpty() 这个条件
pq.poll();
pq.add(tmp);
}
}
}
return new ArrayList<>(pq);
}
}
时间复杂度:O(nlogk) 空间复杂度 O(k)
每次添加元素时,交换次数最大是 logk次。
题目扩展
前k个最大的数
只需要改两处即可
import java.util.*;
public class Solution {
public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
if(input.length==0||k==0){
return new ArrayList<Integer>();
}
PriorityQueue<Integer> pq = new PriorityQueue<>();// 小根堆
for(int i = 0; i<input.length; ++i){
int tmp = input[i];
if(pq.size()<k){
pq.add(tmp);
}else{
if(tmp > pq.peek()){// pq不可能为空 不需要 !pq.isEmpty() 这个条件
pq.poll();
pq.add(tmp);
}
}
}
return new ArrayList<>(pq);
}
}
要求不能重复
1.可以先用hashSet 去重,再生成一个input数组,利用上述方法去做。
2.可以直接排序,得到数组后,从小到大寻找不重复的前k个数。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92876.html