輸入n個整數,找出其中最小的K個數。例如輸入4,5,1,6,2,7,3,8這8個數字,則最小的4個數字是1,2,3,4,。java
首先對數組進行排序,而後取出前k個數。排序方法可選用快速排序,時間複雜度爲O(nl*ogn)。示例代碼:數組
import java.util.ArrayList; import java.util.Arrays;
public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { ArrayList<Integer> list=new ArrayList<>(); if(input.length<k||k==0) return list; Arrays.sort(input); for(int i=0;i<k;i++) list.add(input[i]); return list; } }
首先將這堆數據中前k個數裝入list,並找到這個k個數的最大數max(k),而後從第k+1個數開始向後找,若是有小於這個max(k)的,則替換掉這個數,而後從新這k個數中找出最大的max(k)。這樣一直向後掃描。時間複雜度爲O(k*n)。示例代碼:this
public class Solution_getLeastNumbers { public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> list = new ArrayList<Integer>(); if (input.length < k || k == 0) return list; for (int i = 0; i < k; i++) list.add(input[i]); for (int i = k; i < input.length; i++) { int j = this.getMax(list); int temp = (Integer) list.get(j); if (input[i] < temp) list.set(j, input[i]); } return list; } public int getMax(ArrayList<Integer> list) { int max = list.get(0); int j = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i) > max) { max = list.get(i); j = i; } } return j; } }
掃描數組,每遍找出最小的那個數,複雜度爲O(k*n)。示例代碼:spa
public ArrayList<Integer> GetLeastNumbers_Solution3(int[] input, int k) { ArrayList<Integer> list = new ArrayList<Integer>(); if (input.length < k || k == 0) return list; for (int i = 0; i < input.length; i++) list.add(input[i]); ArrayList<Integer> result=new ArrayList<>(); int num=0; while(num<k) { int minNum=list.get(0); for(int i=0;i<list.size();i++) { if(list.get(i)<minNum) { minNum=list.get(i); } } list.remove((Object)minNum); result.add(minNum); num++; } return result; }
先用數據中的前k個數建一個最大堆,建堆複雜度爲O(k),而後從第k+1個數開始向後掃描,遇到小於堆頂元素時就替換掉堆定元素,更新堆,這個操做的複雜度爲O(logk),總的時間複雜度爲O(k+(n-k)*logk)=>O(n*logk)。示例代碼:.net