zoukankan      html  css  js  c++  java
  • 最小的K个数

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

    实现语言:Java

    import java.util.ArrayList;
    public class Solution {
        public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
            int size=input.length;
            ArrayList<Integer> res=new ArrayList<Integer>();
            if(size==0||input==null||size<k||k<=0){
                return res;
            }
            int start=0;
            int end=size-1;
            int index=partition(input,start,end);
            while(index!=k-1){
                if(index>k-1){
                    end=index-1;
                    index=partition(input,start,end);
                }else if(index<k-1){
                    start=index+1;
                    index=partition(input,start,end);
                }
            }
            for(int i=0;i<k;++i){
                res.add(input[i]);
            }
            return res;
        }
        private int partition(int[] input,int low,int high){
            int pivot=input[low];
            while(low<high){
                while(low<high&&input[high]>=pivot){
                    --high;
                }
                input[low]=input[high];
                while(low<high&&input[low]<=pivot){
                    ++low;
                }
                input[high]=input[low];
            }
            input[low]=pivot;
            return low;
        }
    }
    

     实现语言:Java

    import java.util.ArrayList;
    import java.util.PriorityQueue;
    import java.util.Comparator;
    public class Solution {
        public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
            int size=input.length;
            ArrayList<Integer> res=new ArrayList<Integer>();
            if(size==0||input==null||size<k||k<=0){
                return res;
            }
            PriorityQueue<Integer> maxHeap=new PriorityQueue<Integer>(k,new Comparator<Integer>(){
                @Override
                public int compare(Integer o1,Integer o2){
                    return o2.compareTo(o1);
                }
            });
            for(int i=0;i<size;++i){
                if(maxHeap.size()!=k){
                    maxHeap.offer(input[i]);
                }else{
                    if(maxHeap.peek()>input[i]){
                        maxHeap.poll();
                        maxHeap.offer(input[i]);
                    }
                }
            }
            for(Integer num:maxHeap){
                res.add(num);
            }
            return res;
        }
    }
    
  • 相关阅读:
    some ideas
    zz 牛人啊
    zz 史上最全--各银行借记卡的年费、小额管理费、转账费等!
    哪裡可以買郵票
    : 求靠谱灭蟑螂的方法
    zz 【见闻八卦】《金融时报》年度商业书单:互联网题材占一半
    IOS开发基础知识--碎片6
    IOS开发基础知识--碎片5
    IOS开发基础知识--碎片4
    IOS中关于KVC与KVO知识点
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10198271.html
Copyright © 2011-2022 走看看