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;
    }
}
上一篇:QRCode生成二维码


下一篇:zxing绘制条形码总结