direct java quick select solution


  • 0

    Instead of to find the n - k + 1 smallest, I directly to find the kth largest one.

    public class Solution {
        public int findKthLargest(int[] nums, int k) {
            return quickSelect(nums, 0, nums.length - 1, k);
        }
        public int quickSelect(int[]nums, int low, int high, int k){//find the Kth largest
            int pivot = nums[high];
            int i = low, j = high;
            while(i < j){
                if(nums[i] > pivot)
                    i++;
                else{
                    swap(nums, i, --j);
                }
            }
            swap(nums, i, high);
            int cur = i - low + 1;
            if(cur == k) return nums[i];
            else if(cur > k) return quickSelect(nums, low, i - 1, k);//attention to i - 1
            else return quickSelect(nums, i + 1, high, k - cur);
        }
        public void swap(int[] nums, int i, int j){
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
        }
    }
    

Log in to reply
 

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