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. Git相关、Gitee多人协同开发

    Git相关 1.介绍 ​ 是一个具有版本控制的软件,控制开发的项目代码,具有集群化.多分支的功能 2.对于程序员的作用 协同开发 解决代码合并过程中冲突 代码版本管理 3.git 与 svn 比较 ​ ...

  2. Nginx的重写功能——Rewrite

    Nginx的重写功能--Rewrite https://huaweicloud.csdn.net/63566cced3efff3090b5f470.html?spm=1001.2101.3001.66 ...

  3. 杂:python获取所有盘符简单粗暴版

    def _test_p_get_all_driver():    l = []    for i in range(97, 123):        d = chr(i) + ':\\'        ...

  4. git submodule .gitmodules 子模块

    初始化 git submodule init 添加子项目 git submodule add -b xxxx {path} -b 指定分支 path 可为空 (不知为何, 直接写在 .gitmodul ...

  5. 解决pdf电子签章显示问题(电子发票)

    在/build/pdf.worker.js注释掉一行代码 if (data.fieldType === "Sig") { data.fieldValue = null; // 注释 ...

  6. Android组件化开发-----页面路由(ARouter)

    平时开发中,我们经常用到页面跳转功能.之前我一直使用Intent过跳转 Intent intent = new Intent(A.this, B.class); intent.putExtra(&qu ...

  7. (K8s学习笔记三)创建Namespace

    Namespace(命名空间)很多情况下用于实现多租户的资源隔离.Namespace通过将集群内部的资源对象"分配"到不同的Namespace中,形成逻辑上分为不同项目.小组或用户 ...

  8. yaml 文件的读取写

    yaml 是一种数据格式, 它可以和json数据相互转化 . 自动化测试中一般用于做配置文件或是测试用例. 数据的组成, 两种格式: 1. 字典 2. 列表 Eg. config.yaml serve ...

  9. python读取文本中的字典

    首先得明确文本的每行是存的json或者用python的write(str(一个字典))写入的,那么不用借助json模块就能读取为字典,使用eval函数就行,json只能处理带双引号的字符串,但很多时候 ...

  10. OpenCV Mat类数据存储方式

    参考BiliBili 于仕琪老师 avoid-memory-copy-in-opencv class CV_EXPORTS Mat { public: // some members int rows ...