Java 15ms solution using quick select


  • 0
    F
    public class Solution {
    	public int findKthLargest(int[] nums, int k) {
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 0; i < nums.length; i++) {
                list.add(nums[i]);
            }
            return qSelect(list, k);
        }
        private int qSelect(List<Integer> nums, int k) {
            // Get random pivot from 0 to nums.size()-1.
            int pivot = nums.get(java.util.concurrent.ThreadLocalRandom.current().nextInt(0, nums.size()));
            List<Integer> pileLessThanPivot = new ArrayList<Integer>();
            List<Integer> pileGreaterThanPivot = new ArrayList<Integer>();
            for (int i = 0; i < nums.size(); i++) {
                if (nums.get(i) < pivot) {
                    pileLessThanPivot.add(nums.get(i));
                } else if (nums.get(i) > pivot) {
                    pileGreaterThanPivot.add(nums.get(i));
                }
            }
            if (pileGreaterThanPivot.size() >= k) {
                return qSelect(pileGreaterThanPivot, k);
            } else if (pileLessThanPivot.size() + k > nums.size()) {
                return qSelect(pileLessThanPivot, k - (nums.size() - pileLessThanPivot.size()));
            } else {
            	return pivot;
            }
        }
    }

Log in to reply
 

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