java---最小的K個數


時間限制:1秒 空間限制:32768K
題目描述
輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。
最簡單的思路當然是直接排序,最前面的K個數就是題目所求,但是這顯然不是優秀的解法。
可以選擇使用快排的Partition函數,簡單划分,但是並不排序,較為快速的解決問題。
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> result=new ArrayList<Integer>();
        if(k<=0){
            return result;
        }
        if(input.length==0||input.length<k){
            return result;
        }
        int start=0;
        int end=input.length-1;
        int index=Partition(input,start,end);
        while(index!=k-1){
            if(index>k-1){
                end=index-1;
                index=Partition(input,start,end);
            }else{
                start=index+1;
                index=Partition(input,start,end);
            }
        }
        for(int i=0;i<k;i++){
            result.add(input[i]);
        }
        return result;
    }
    public int Partition(int[] input,int start,int end){
        int pivot=input[start];
        while(start<end){
            while(start<end&&input[end]>=pivot){--end;}
                input[start]=input[end];
            while(start<end&&input[start]<=pivot){++start;}
                input[end]=input[start];
        }
        input[end]=pivot;
        return end;
    }
}

還可以考慮使用另一種數據結構,最大堆,用最大堆保存這k個數,每次只和堆頂比,如果比堆頂小,刪除堆頂,新數入堆。

import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Comparator;
public class Solution {
   public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) {
       ArrayList<Integer> result = new ArrayList<Integer>();
       int length = input.length;
       if(k > length || k == 0){
           return result;
       }
        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 < length; i++) {
            if (maxHeap.size() != k) {
                maxHeap.offer(input[i]);
            } else if (maxHeap.peek() > input[i]) {
                Integer temp = maxHeap.poll();
                temp = null;
                maxHeap.offer(input[i]);
            }
        }
        for (Integer integer : maxHeap) {
            result.add(integer);
        }
        return result;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM