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. (0319) uvmgen的使用,产生的UVM环境介绍

    qq https://blog.csdn.net/hh199203/article/details/118210541

  2. 哲讯科技携手江苏大摩半导体借助SAP ERP打造数字化转型升级

    项目启动会2022年10月28日,无锡哲讯科技携手江苏大摩半导体科技有限公司SAP ERP系统实施项目启动大会于江苏大摩的上海总部会议室胜利召开.双方项目组核心成员,共同见证了本次SAP ERP实施项 ...

  3. tidb 杂记

    tidb_biuil_stats_concurrency 执行analyze table时会分成多个小任务,可以同时执行的任务数量.tidb_distsql_scan_concurrency 在执行分 ...

  4. 读后笔记 -- Python 全栈测试开发 Chapter7:移动自动化测试框架

    7.1 主流框架优缺点剖析 1. APP 主要测试策略 安装.卸载测试: 安装:1)安装路径:2)安装环境(平台.安全软件):3)安全权限(获取位置.摄像头.通讯录.ROOT管理员等权限):4)安装的 ...

  5. MySQL中的sql优化

    目标: 掌握SQL调优的原则 掌握SQL调优的基本逻辑 掌握优秀SQL的编写方案 掌握何为慢SQL以及检测方案 SQL优化原则 1.减少数据量(表中数据太多可以分表,例如超过500万数据  双11一个 ...

  6. fpga always赋值

  7. 关闭内核Debug_log打印!

    echo 0 > /proc/sys/kernel/printk  \r

  8. 嵌入式C设计模式 - 观察者模式

    当对象间存在一对多关系时,则使用观察者模式(Observer Pattern).比如,当一个对象被修改时,则会自动通知依赖它的对象.观察者模式属于行为型模式. 1.观察者模式解决一对多的问题,例如一个 ...

  9. python的排序问题

    python的排序方法有两个 1 nums.sort() # 原数组上排序, 没有返回值, nums变为有序 2 # 或者 3 nums = sorted(nums) # 原数组不变, 会返回一个排好 ...

  10. 几十行代码实现简易版koa~

    application.js const http = require("http")// 洋葱模型 function compose(middleware){ return fu ...