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. Java基础学习:5、递归

    1.递归:就是方法自己调用自己. public class Test01 { public void test(int n) { if (n > 2) { test(n -1); } Syste ...

  2. k8s Service yaml文件编写

    apiVersion: app/v1 #API的版本号,版本号可以用 kubectl api-versions 查询到 kind: Service #表明资源对象,例如Pod.RC.Service.N ...

  3. android判断是否连接wifi跟网络状态的判断及wifi信号强度的方法

    场景:android判断是否连接wifi跟网络状态的判断 android判断是否连接wifi和网络状态的判断 // 是否连接WIFI public static boolean isWifiConne ...

  4. (原创)Onlyoffice docs docker实例安装示例后,打开文档提示:文档下载失败

    不能使用localhost.请用本机ip访问

  5. 51电子-STC89C51开发板:安装KEIL

    全部内容,请点击: 51电子-STC89C51开发板:<目录> ---------------------------  正文开始  --------------------------- ...

  6. 05 Java 数组

    Java 数组 一.什么是数组 数组是相同类型数据的有序集合 数组描述的是相同类型的若干个数据,按照一定的顺序排列组合而成 其中每一个数据称为数组元素,每个数组元素可以通过下标来访问它们 二.数组的声 ...

  7. pillow 创建图片并添加一些自定义信息

    from PIL import Image vm = Image.new('RGBA', (dshape[1], dshape[0])) vm = Image.fromarray(np.array(s ...

  8. usb 2.0枚举过程

    device枚举过程: hub枚举过程:

  9. Python使用pip安装第三方模块问题

    安装时总会出现错误:pip is configured with locations that require TLS/SSL, however the ssl module in Python is ...

  10. java创建对象时内存发生了什么

    Student s = new Student();\ 把Student.class文件加载到内存 在栈内存给s变量开辟一个空间 在堆内存为学生对象申请一个空间 给成员变量进行默认初始化 给成员变量显 ...