求一個數組中最小的K個數字
阿新 • • 發佈:2019-01-04
用快排思想:
import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; class Solution { public void solve(ArrayList<Integer> res,int[] input,int left,int right,int k) { int t; int i=left; int j=right; int temp=input[left]; while(i<j) { i=i+1; while(input[i]<temp&&i<right) i++; while(input[j]>temp&&j>left) j--; if(i<j) { t=input[i]; input[i]=input[j]; input[j]=t; } } if(j>=left&&i<=right) { t=input[left]; input[left]=input[j]; input[j]=t; } if(j+1==k) { for(int u=0;u<k;u++) res.add(input[u]); return; } if(j+1>k&&j>left) solve(res,input,left,j-1,k); if(j+1<k&&i <right) solve(res,input,j+1,right,k); } public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> res=new ArrayList<Integer>(); if(input.length==k) for(int i=0;i<input.length;i++) res.add(input[i]); else if(input.length!=0) solve(res,input,0,input.length-1,k); return res; } }
用最大堆儲存這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; } }