O(N) TIME, find Kth smallest element

1. Kth Largest Element in an Array

//from 0th, 1th ...

public class Solution {
    public int findKthLargest(int[] nums, int k) {

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

    public int findKthSmallest(int[] nums, int s, int e, int k) {

        if(s > e) return -1;

        int pivot = nums[e];
        int left  = s;
        for(int i = s; i <e ; i ++){
            if(nums[i] < pivot)
                swap(nums, left++, i);
        }

        swap(nums, left, e);
        if(left == k)   
            return nums[left];
        else if(left < k)
            return findKthSmallest(nums, left + 1, e, k);
        else
            return findKthSmallest(nums, s, left - 1, k);

    }

    public void swap(int[] nums, int i, int j) {

        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

results matching ""

    No results matching ""