Find the K smallest numbers in an unsorted integer array A. The returned numbers should be in ascending order.

Assumptions

  • A is not null
  • K is >= 0 and smaller than or equal to size of A

Return

  • an array with size K containing the K smallest numbers in ascending order

Examples

  • A = {3, 4, 1, 2, 5}, K = 3, the 3 smallest numbers are {1, 2, 3}

public class Solution {
// use a priority queue(max heap with size of k) to figure it out.
// we traverse the array one time, whenever we met a element, we check it if smaller then the top element of the heap
// if it is, we poll and insert that new element in
// if it isn't, we do nothing
// time: O(n)
// space: O(k)
//
// thing to konw better: the vanilla priority q in java is max heap or min heap?
// how to turn a priority q into a array or a list in a efficient way?
//
// assumption: all element in array is integer and small than Integer.MAX_VALUE and larger than Integer.MIN_VALUE
// array is not null, array's length can be 0
// k can be zero, k is not larger than the length of array
public int[] kSmallest(int[] array, int k) {
// Write your solution here
int[] res = new int[k];
if(k==0){
return res;
}
PriorityQueue<Integer> pq = new PriorityQueue<>(k,Collections.reverseOrder());
for(int i=0; i<array.length; i++){
if(pq.size()<k){
pq.offer(array[i]);
}else{
if(array[i]<pq.peek()){
pq.poll();
pq.offer(array[i]);
}
}
}
for(int i=0; i<k; i++){
res[k-i-1] = pq.poll();
}
return res;
}
}

K Smallest In Unsorted Array的更多相关文章

  1. find K maximum value from an unsorted array(implement min heap)

    Maintain a min-heap with size = k, to collect the result. //Find K minimum values from an unsorted a ...

  2. UVA-11997 K Smallest Sums

    UVA - 11997 K Smallest Sums Time Limit: 1000MS   Memory Limit: Unknown   64bit IO Format: %lld & ...

  3. D - K Smallest Sums(多路归并+贪心)

    Problem K K Smallest Sums You're given k arrays, each array has k integers. There are kk ways to pic ...

  4. 【暑假】[实用数据结构]UVa11997 K Smallest Sums

    UVa11997 K Smallest Sums  题目: K Smallest Sums You're given k arrays, each array has k integers. Ther ...

  5. 11997 - K Smallest Sums(优先队列)

    11997 - K Smallest Sums You’re given k arrays, each array has k integers. There are kk ways to pick ...

  6. [Algorithm] How to use Max Heap to maintain K smallest items

    Let's say we are given an array: [,,,,,,] We want to get K = 3 smallest items from the array and usi ...

  7. [Algorithm] Find Nth smallest value from Array

    Q1: Find the smallest value from array: function findMin(arr) { let min = arr[0]; for (let i = 1; i ...

  8. UVa 11997 K Smallest Sums 优先队列&amp;&amp;打有序表&amp;&amp;归并

    UVA - 11997 id=18702" target="_blank" style="color:blue; text-decoration:none&qu ...

  9. Why is processing a sorted array faster than an unsorted array?

    这是我在逛 Stack Overflow 时遇见的一个高分问题:Why is processing a sorted array faster than an unsorted array?,我觉得这 ...

  10. Kth Smallest Element in Unsorted Array

    (referrence: GeeksforGeeks, Kth Largest Element in Array) This is a common algorithm problem appeari ...

随机推荐

  1. WOW事件大全(翻译对照)

    魔兽世界(WOW)插件开发事件大全 ACHIEVEMENT_EARNED 取得的成就 ACHIEVEMENT_SEARCH_UPDATED 已更新成就搜索 ACTIONBAR_HIDEGRID 动作条 ...

  2. htmlApk:一个轻松在线打包生成双端app应用的网站

    htmlApk平台,基于HTML打包制作APP,只要有手机网站或者HTML文件,3分钟即可生成app多端应用,同时拥有苹果版和安卓版双系统APP,快速进入移动互联时代. 全面支持h5网址打包,可设置图 ...

  3. 虚拟机搭建linux环境&&使用winscp连接搭建好的linux环境步骤

    一.需要的工具 虚拟机应用程序.一个镜像(ubuntu等).winscp可执行程序 二.安装虚拟机以及插入镜像 1)选择虚拟机 我安装的是VMware 就是这个,因为之前用的都是vitualbox现在 ...

  4. sxt_(003_007)_tomcat

    一.web服务器 接受浏览器请求,进行结果响应. 常见的web服务器:tomcat.jboss.weblogic.websphere.resin.jetty.二.tomcat下载: 去apache官网 ...

  5. js match方法

    1.用法 match()方法可以字符串中检索指定的值,或者是匹配一个或多个正则表达式 2.返回值 该方法类似于indexOf()/lastIndexOf(),区别就是返回值不一样 indexOf()/ ...

  6. 【当年笔记】集合之Queue队列

    1)Queue 分类 双端队列:双端队列(Deque)是 Queue 的子类也是 Queue 的补充类,头部和尾部都支持元素插入和获取. 阻塞队列:阻塞队列指的是指添加或删除元素时,如果没有成功,会阻 ...

  7. SAP 附件功能 PRD环境无法删除 VIEW_ATTA

    如图:界面上面没有打勾确认按钮 解决方案:来源网址 How to disable, delete and edit buttons function in attachment list. | SAP ...

  8. win10 校验MD5值

    CertUtil -hashfile C:\xxxxx\xxx.xxx MD5   // C:\xxxxx\xxx.xxx为文件路径

  9. (python)python 3.9 安装 robotframework-ride 因为 wxPython 失败

    1. 正常安装方式 1)安装 robotframework pip install robotframework 2) 安装 robotframework-ride pip install robot ...

  10. Freertos stack-overflow 检测

    (出现的地址信息没有特定意义,仅供参考) vApplicationStackOverflowHook() at rtos.c:371 0x55aa vTaskSwitchContext() at ta ...