Any improment about the solution?


  • 1
    L
    public class Solution {
    public int findKthLargest(int[] nums, int k) {
        
        int p = 0;
        int q = nums.length - 1;
        int res = partition(nums, p, q);
        while(q - res + 1 != k) {
            if(q - res + 1 > k) {
                p = res + 1;
                res = partition(nums, p, q);
            } else if(q - res + 1 < k) {
                k = k - (q - res + 1);
                q = res - 1;
                res = partition(nums, p, q);
            } else {
                return nums[res];
            }
        }
        return nums[res];
    }
    
    public int partition(int[] nums, int start, int end) {
    
        int target = nums[start];
        int i = start;
        int j = end;
        while(i < j) {
            while(i < j && nums[j] >= target) j--;
            if(i < j) nums[i++] = nums[j];
            while(i < j && nums[i] < target) i++;
            if(i < j) nums[j--] = nums[i];
        }
        nums[i] = target;
        return i;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.