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. AcWing 791. 高精度加法C++数组实现

    高精度加法 a, b均为正整数 #include <iostream> using namespace std; const int N = 100010; int A[N], B[N], ...

  2. vite + vue3 + js + xlsx 导出excel

    安装依赖 1 npm install xlsx --save 使用版本 封装js /* 导出excel文件 */ /** * 导出excel文件实现思路分析 * * 1.通过XLSX插件的 XLSX. ...

  3. 分布式锁 -- redis

    原理 redis设置一个key和value,如果存在则获取锁失败,不存在则获取锁成功处理业务,业务处理完成后删除这条数据,可以带个失效时间. 代码 public void handleInvoice( ...

  4. windows 2012 打补丁升级后不能启动处理

    如果可以进入WinRE这个修复的高级选项,选择安全模式,是否可以进入,卸载最近安装的补丁,再重启看一下. 如果无法进入安全模式的话,那么选择cmd模式,使用下方命令.这通常会回退pending的upd ...

  5. windows 10 使用Ghost 恢复系统,安装bcd修复引导

    使用windows10安装盘启动,进入系统修复选项,使用cmd X:Source\,那说明进入了管理者模式,然后按照以下步骤依次输入: 1.diskpart 2.sel disk 03.list pa ...

  6. h5页面回到顶部

    1.锚点 <aname="top"></a> <ahref="#top"></a> 2.回到顶部 documen ...

  7. 三星电子的KNOX安全技术难以满足企业BYOD控管需求

    不可否认的是三星在智能手机领域里的辉煌战绩,三星最近推出了端到端的基于Android平台的解决方案KNOX,并且宣称可以提供从硬件到应用层的多重安全加固. KNOX是否能够延续其在企业领域里辉煌呢?相 ...

  8. MySQL 5.7升级8.0过程(详解)

    记一次MySQL 5.7升级8.0的详细过程,聊聊我的思路,希望可以帮助大家. 以一个例子为切入点 一.升级背景 为什么要升级到MySQL8.0?大概多久进行一次? 大家可以参考下图记录的各个版本的发 ...

  9. windows下创建con文件夹

    有时候,我们会碰到必须创建一个名为CON的文件夹,而这个名称在Windows下属于保留字(DOS时代的遗留产物). 方法如下: 1.打开命令行窗口(开始-->运行-->cmd) 2.输入完 ...

  10. SAP 结构转JSON

    *使用方式 jsonstr = zui2_json=>serialize( data = ls_in compress = abap_true pretty_name = zui2_json=& ...