leetcode -- 215. Kth Largest Element in an Array

题目描述

题目难度:Medium
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.

  • Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

  • Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note:
You may assume k is always valid, 1 ≤ k ≤ array’s length.

AC代码

利用快速排序的思路

class Solution {
    public int findKthLargest(int[] nums, int k) {
        if(nums == null || nums.length == 0) return -1;
        return quickSort(nums, k , 0, nums.length - 1);
    }
    
    private int quickSort(int[] nums, int k, int start, int end){
        int tmp = nums[start];
        int low = start, high = end;
        while(low < high){
            while(low < high && nums[high] >= tmp) high--;
            if(low < high) nums[low] = nums[high];
            while(low < high && nums[low] <= tmp) low++;
            if(low < high) nums[high] = nums[low];
        }
        nums[low] = tmp;
        if(low == nums.length - k) return tmp;
        else if(low < nums.length - k) return quickSort(nums, k, low + 1, end);
        else return quickSort(nums, k, start, low - 1);
    }
}

猜你喜欢

转载自blog.csdn.net/tkzc_csk/article/details/85778209