描述
有一个整数数组,请你根据快速排序的思路,找出数组中第 k 大的数。
给定一个整数数组 a ,同时给定它的大小n和要找的 k ,请返回第 k 大的数(包括重复的元素,不用去重),保证答案存在。
要求:时间复杂度 O(nlogn)O(nlogn),空间复杂度 O(1)O(1)
数据范围:0\le n \le 10^50≤n≤105, 1 \le K \le n1≤K≤n,数组中每个元素满足 0 \le val \le 10^90≤val≤109
示例1
输入:[1,3,5,2,2],5,3
复制返回值:2
示例2
输入:[10,10,9,9,8,7,5,6,4,3,4,2],12,3
返回值:9
说明:去重后的第3大是8,但本题要求包含重复的元素,不用去重,所以输出9
分析:
可以选择快排将数组排序,然后取第k-1个。
改进:
快排算法中取得分位点p以后,与k相比较,若p小于k则迭代时将p+1到end部分进行迭代;若p大于k则迭代begin到p-1部分。
import java.util.*;
public class Solution {
public int findKth(int[] a, int n, int K) {
// write code here
int kth =QuickSort(a,0,n-1,K-1);
return kth;
}
public int QuickSort(int[] arr,int begin,int end,int K){
if(begin >= end){
return arr[begin];
}
int pivot = findLocation(arr,begin,end);
if(pivot == K){
return arr[pivot];
}
else if(pivot < K){
return QuickSort(arr,pivot+1,end,K);
}
else
return QuickSort(arr,begin,pivot-1,K);
}
public int findLocation(int[] arr,int begin,int end){
int key = arr[end];
int index = begin - 1;
for(int i = begin;i <= end;i++){
if(arr[i] > key) {
index++;
Swap(arr,index,i);
}
if(arr[i] <= key) continue;
}
Swap(arr,++index,end);
return index;
}
public void Swap(int[] arr,int before,int after){
int temp = arr[before];
arr[before] = arr[after];
arr[after] = temp;
return;
}
}
改进:
选用堆排序,最大堆排序,选择第K次排序后的堆顶元素。
import java.util.*;
public class Solution {
public int findKth(int[] a, int n, int K) {
// write code here
for(int i = 0;i < K;i++){
buildHeap(a,0,a.length - i);
Swap(a,0,a.length-1 - i);
}
return a[a.length - K];
}
public void buildHeap(int[] arr,int root,int length){
int left = 2*root + 1;
int right = 2*root + 2;
if(left < length){
buildHeap(arr,left,length);
if(arr[left] > arr[root])
Swap(arr,left,root);
}
if(right < length){
buildHeap(arr,right,length);
if(arr[right] > arr[root])
Swap(arr,right,root);
}
return;
}
public void Swap(int[] arr,int before,int after){
int temp = arr[before];
arr[before] = arr[after];
arr[after] = temp;
return;
}
}