【剑指 Offer 】40. 最小的k个数

    科技2024-06-02  72

    题目:40. 最小的k个数

    思路 大顶堆:堆顶元素就是堆中所有元素中最大的那个元素。 遍历数组:

    如果堆中元素不足K个,那么就是直接添加;当堆中元素大于等于K个时,就要将堆顶元素与遍历到的当前元素比较: 比栈顶元素大就跳过;比栈顶元素小,那么栈就弹出栈顶元素,然后将该元素放入栈中; class Solution { public int[] getLeastNumbers(int[] arr, int k) { // 特判 if(k == 0 || k > arr.length){ return new int[0]; } // 优先队列默认是小顶堆: // Queue<Integer> heap = new PriorityQueue<>(); //创建大顶堆: Queue<Integer> heap = new PriorityQueue<>(k,(x,y)->(y-x)); //把最小的k个数存到heap中 for(int num : arr){ if(heap.size() < k){ heap.offer(num); }else if(heap.peek() > num){ heap.poll(); heap.offer(num); } } //从heap中取出存放在数组中 int[] res = new int[k]; int i = 0; for(Integer e : heap){ res[i] = e; i ++; } return res; } }
    Processed: 0.009, SQL: 9