二分查找(六)——无序数组也能二分查找?

LeetCode_215_KthLargestElementinanArray

题目分析:

您还记得当年写过的快排吗?虽然不是最快的思路,确是本题的初衷。利用快排的操作,将问题分治。

解法:

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

public static int partition(int[] nums, int left, int right){
    int pivot = nums[left], l = left +1, r = right;
    while (l <= r){
        if(nums[l] < pivot && nums[r] > pivot)
            swap(nums, l, r);
        if (nums[r] <= pivot) r--;
        if (nums[l] >= pivot) l++;
    }
    swap(nums, left, r);

    return r;
}

public static void swap(int nums[], int left, int right){
    int temp = nums[left];
    nums[left] = nums[right];
    nums[right] = temp;
}

你可能感兴趣的:(二分查找(六)——无序数组也能二分查找?)