Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
53 lines (40 loc) · 1.21 KB

215.md

File metadata and controls

53 lines (40 loc) · 1.21 KB

215. Kth Largest Element in an Array

Description

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example, Given [3,2,1,5,6,4] and k = 2, return 5.

**Note: ** You may assume k is always valid, 1 ? k ? array's length.

Thinking Process

  1. Use quicksort variation of quickSelect to find the target element

Code

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        return quickFind(nums, 0, nums.length - 1, k);
    }
    
    int quickFind(int[] nums, int low, int high, int k){
        int pivot = nums[low];
        int i = high + 1;
        
        for(int j = high; j > low; j--){
            if(nums[j] <= pivot){
                i--;
                swap(nums, i, j);
            }
        }
        
        swap(nums, low, i - 1);
        if(i == k){
            return pivot;
        }else if(i < k){
            return quickFind(nums, i, high, k);
        }else{
            return quickFind(nums, low, i - 2, k);
        }   
    }
    
    void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}