标签:简单 offer for 题目 最小 compareto style else wrap
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; } }
标签:简单 offer for 题目 最小 compareto style else wrap
原文地址:http://www.cnblogs.com/zzmher/p/7730700.html