zoukankan      html  css  js  c++  java
  • K Smallest In Unsorted Array

    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;
      }
    }
  • 相关阅读:
    Android Studio使用教程
    http://www.android-doc.com/#/295
    JDK,JRE,JVM区别与联系(ZZ)
    eclipse下载
    mac下android环境搭建笔记(android studio)
    android环境配置
    JDK、JRE、JVM三者间的关系
    实体类作用、封装与面向对象思想
    领域模型中的实体类分为四种类型:VO、DTO、DO、PO
    [架构设计] 组件和模块的区别
  • 原文地址:https://www.cnblogs.com/zg1005/p/12131315.html
Copyright © 2011-2022 走看看