• 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;
      }
    }
  • 相关阅读:
    算法-回溯法
    算法-动态规划=背包问题
    算法-贪心算法
    算法-KMP模式匹配算法
    算法-两点之间最短路径
    Hibernate学习笔记
    MyBatis一级缓存和二级缓存
    使用MyBatis-Gererator自动生成Dao.Model.Mapping相关文件
    MyBatis中一对多和多对一的学习详解
    MyBatis中使用添加判断进行查询
  • 原文地址:https://www.cnblogs.com/zg1005/p/12131315.html
Copyright © 2020-2023  润新知