剑指offer 最小的K个数

主宰稳场 提交于 2020-01-30 07:04:04

题目
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4,。

思路
1 利用大顶堆保存这k个数
2 遍历input数组,每次与堆顶元素比较,若堆顶元素比较大,则删除堆顶元素,把input元素加入堆

import java.util.*;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {      
        ArrayList<Integer> ans=new ArrayList();
        if(k<1||k>input.length)
            return ans;
        
        PriorityQueue <Integer> maxHead=new PriorityQueue<Integer>(k,new Comparator<Integer>(){
            public int compare(Integer o1,Integer o2){
                return o2.compareTo(o1);
            }
        });
        
        for(int i=0;i<input.length;i++){
            if(maxHead.size()!=k)
                maxHead.offer(input[i]);
            else{
                if(maxHead.peek()>input[i])
                {
                    maxHead.poll();
                    maxHead.offer(input[i]);
                }
            }
        }
       for(Integer i:maxHead)
           ans.add(i);
       return ans;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!