Kth Largest Element in an Array(第K大數(shù))

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
該題可以使用基于快速排序分治思想來(lái)解決這個(gè)問(wèn)題。第k大數(shù)可以等價(jià)為第m=nums.length-k小的數(shù)。
快速排序的每次過(guò)程可以確定一個(gè)數(shù)的位置,假設(shè)這個(gè)位置為pos,那么m和這個(gè)pos應(yīng)該有三種關(guān)系。

pos == m 那么第m小的數(shù)就為nums[pos]

pos < m 說(shuō)明第m小的數(shù)在pos的右邊,也就是比nums[pos]大

pos > m 說(shuō)明第m小的數(shù)在pos的左邊,也就是比nums[pos]小

由此思路可以得出以下代碼

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        return findKthLargest(nums, nums.length-k, 0,nums.length-1);
    }
    
    public int findKthLargest(int[] nums, int k, int low, int high) {
        if(low>high)
            return -1;
        int pos = partition(nums, low, high);
        if(pos == k){
            return nums[pos];
        }else if(pos < k){
            return findKthLargest(nums, k, pos+1, high);
        }else{
            return findKthLargest(nums, k, low, pos-1);
        }
        
    }
    
    
    public int partition(int[] nums, int low, int high){//每次給數(shù)組進(jìn)行劃分
        int pivot = nums[low];
        int i = low, j = high;
        while(i < j){
            while (i < j && nums[j]>=pivot){
                j--;
            }
            while(i < j && nums[i]<=pivot){
                i++;
            }
            if(i < j){
                swap(nums, i, j);
            }
        }
        swap(nums, i,low);
        return i;        
    }
    
    public void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容