zoukankan      html  css  js  c++  java
  • leetcode-面试题40

    这个题用Java的一些特殊数据结构来做是很简单的,如果加一个思想就是最大堆思想。

    class Solution {
        public int[] getLeastNumbers(int[] arr, int k) {
            if (k == 0) {
                return new int[0];
            }
            Queue<Integer> heap = new PriorityQueue<>(k, (i1, i2) -> Integer.compare(i2, i1));
    
            for (int e : arr) {
                if (heap.isEmpty() || heap.size() < k || e < heap.peek()) {
                    heap.offer(e);
                }
                if (heap.size() > k) {
                    heap.poll(); 
                }
            }
    
            int[] res = new int[heap.size()];
            int j = 0;
            for (int e : heap) {
                res[j++] = e;
            }
            return res;
        }
    }

    end

    一个没有高级趣味的人。 email:hushui502@gmail.com
  • 相关阅读:
    node
    ionic
    关于websocket和ajax无刷新
    HTML图片热区
    npm -D -S -g -i 以及安装技巧
    es6 webpack转es5
    es6
    es6
    ssh tunnel
    vim上次和下次光标位置
  • 原文地址:https://www.cnblogs.com/CherryTab/p/12535825.html
Copyright © 2011-2022 走看看