其他分享
首页 > 其他分享> > lintcode 5 · Kth Largest Element

lintcode 5 · Kth Largest Element

作者:互联网

https://www.lintcode.com/problem/5/?_from=cat

[]
what is the bug?

[code]

public class Solution {
    /**
     * @param k: An integer
     * @param nums: An array
     * @return: the Kth largest element
     */
    public int kthLargestElement(int k, int[] nums) {
        // write your code here

        return kthLargestElement(k, nums, 0, nums.length-1);
    }

    int kthLargestElement(int k, int[] nums, int l, int r){
        
        int pInx = partition(nums, l, r);
        int len = nums.length;
        if(pInx > len - k){
            int rlen = len-1 - pInx;
            return kthLargestElement(k-rlen-1, nums, l, pInx-1);
        }
        if(pInx < len - k){
            return kthLargestElement(k, nums, pInx+1, r);
        }
        return nums[pInx];
    }

    int partition(int[] nums, int left, int right){
        
        int pivot = nums[left];
        int l = left + 1;
        int r = right;

        while(l < r){
            if(nums[l] < pivot){
                l++;
                continue;
            }
            if(nums[r] >= pivot){
                r--;
                continue;
            }
            swap(nums, l, r);
            l++;
            r--;
        }
        if(nums[l]>=pivot){
            l--;
        }
        swap(nums, left, l);
        return l;
    }

    void swap(int[] arr, int i, int j){
        
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
}

标签:arr,return,nums,int,lintcode,Element,pInx,Kth,kthLargestElement
来源: https://blog.csdn.net/laohixdxm00/article/details/120792626