(頭條)
最小的第K個數也是和這題topK一樣的思路
1、全排序 時間復雜度O(nlogn)
2、Partiton思想 時間復雜度O(n) (因為不需要像快排一樣對所有的分段都兩兩Partition)
基於數組的第k個數字來調整,使得比第k個數字小的所有數字都位於數組的左邊,比第k個數字大的所有數字都位於數組的右邊。調整之后,位於數組左邊的k個數字就是最小的k個數字(這k個數字不一定是排序的)。O(N)
3、最大堆 時間復雜度O(nlogk)
Java堆用優先隊列PriorityQueue實現
4、如果用冒泡排序,時間復雜度為O(n*k)
1、全排序 時間復雜度O(nlogn)
Arrays.sort()
3、最大堆 時間復雜度O(nlogk)
用最大堆保存這k個數,每次只和堆頂比,如果比堆頂小,刪除堆頂,新數入堆。
鏈接:https://www.nowcoder.com/questionTerminal/6a296eb82cf844ca8539b57c23e6e9bf 來源:牛客網 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; } }
2、Partiton思想 時間復雜度O(n)
鏈接:https://www.nowcoder.com/questionTerminal/6a296eb82cf844ca8539b57c23e6e9bf
利用快速排序中的獲取分割(中軸)點位置函數Partitiion。
基於數組的第k個數字來調整,使得比第k個數字小的所有數字都位於數組的左邊,比第k個數字大的所有數字都位於數組的右邊。調整之后,位於數組左邊的k個數字就是最小的k個數字(這k個數字不一定是排序的)
時間復雜度O(n) :一遍partition是O(N)的很容易證明。求第k大數的時候,pivot的不滿足條件的那一側數據不需要再去處理了,平均時間復雜度為O(N+N/2+N/4+...)=O(N)。而快排則需要處理,復雜度為O(nlogn)。
import java.util.*; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { ArrayList<Integer> list = new ArrayList(); if(input.length==0||input.length<k||k<=0){ return list; } int index = partition(input,0,input.length-1,k); int low = 0; int high = input.length-1; while(index!=k-1){ if(index>k-1){ high = index-1; index = partition(input,low,high,k); } else if(index<k-1){ low = index+1; index = partition(input,low,high,k); } } for(int i=0;i<k;i++){ list.add(input[i]); } return list; } public int partition(int[] array,int low,int high,int k){ int temp = array[low]; while(low!=high){ while(low<high&&array[high]>=temp) high--; array[low] = array[high]; while(low<high&&array[low]<=temp) low++; array[high] = array[low]; } array[low] = temp; return low; } }
