Leetcode---陣列中的第K個最大元素--隨機化演算法
阿新 • • 發佈:2018-12-08
陣列中的第K個最大元素
題目連結:陣列中的第K個最大元素
思路:
- 如果先排序,不管利用哪個,比較排序時間複雜度最優為O(nlgn)
- 但是我們發現,快排的一趟排列有一定的性質,我們可以求得一趟快排之後,該數在整個陣列中排在第幾位,且將整個陣列劃分為兩段
- 利用這個性質,我們可以單側截斷,遞迴查詢第K個最大元素
- 但是這個演算法並不是最優的,因為他和陣列的原始狀況有關,原始陣列最壞為逆序狀態下,演算法複雜度為O(n ^2)
- 改進時加入隨機化演算法,不直接將第一個元素作為關鍵數,而是隨機產生陣列中的一個數作為關鍵數
public static int findKthLargest(int[] nums, int k) {
return sort(nums,0,nums.length-1,k);
}
public static int sort(int[] nums,int first,int last,int k) {
//在範圍內產生隨機數,和第一個數字交換
int exch = (int) (first+Math.random()*(last-first+1));
int temp_exc = nums[exch];
nums[exch] = nums[first];
nums[first] = temp_exc;
//記錄第一個數字
int temp = nums[first];
int rear = last,front = first;
while(front<rear) {
//從後往前找小數
while(nums[rear]>=temp&&front<rear)rear--;
// System.out.println(rear);
//此時找到第一個小數
nums[front] = nums[rear];
while(nums[front]<=temp&&front<rear) front++;
// System.out.println(front);
//此時找到第一個大數
nums[rear] = nums[front];
}
nums[front] = temp;
// for(int n:nums) {
// System.out.print(n+" ");
// }
if(last-front+1==k) {
return nums[front];
}else if(last-front+1>k) {
return sort(nums, front+1, last, k);
}else {
return sort(nums, first, front-1, k-last+front-1);
}
}