LeetCode215 数组中第K大的元素

  1. Kth Largest Element in an Array
    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.

快速排序的方法:时间复杂度O(n)

public int findKthLargest(int[] nums, int k) {
    k = nums.length - k;
    int left = 0;
    int right = nums.length - 1;
    while(left < right){
        int j = partition(nums,left,right);
        if(j == k) break;
        else if(j > k){
            right = j - 1;
        }else{
            left = j + 1;
        }
    }
    return nums[k];
}

private int partition(int[] nums, int lo, int hi) {
    int pivot = nums[lo];
    int i = lo + 1;
    int j = hi;
    while (lo < hi){
        while(i < hi && nums[i] <= pivot) i++; //和pivot相等的数应该看作小于pivot
        while(j > lo && nums[j] > pivot) j--;
        if(i >= j) break;
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    int temp = nums[lo];
    nums[lo] = nums[j];
    nums[j] = temp;
    return j;
}

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/84836562