• 最小的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;
        }
    }
    
  • 相关阅读:
    Spring Boot从Controller层进行单元测试
    CentOS7搭建Flume1.6环境
    CentOS7安装Zookeeper3.4.11+HBase1.3.3
    Hadoop1.x的单点问题与Hadoop2.x HA原理
    Hadoop2.x——Yarn原理
    CentOS7安装scala2.11.8+spark2.0.2
    CentOS7搭建Hive1.2.2+mysql5.7
    搭建集群环境(CentOS7+Hadoop2.6.1+SSH)
    消除“if...else”实战
    SpringCloud Eureka服务治理机制
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10198271.html
Copyright © 2020-2023  润新知