leetcode 215. Kth Largest Element in an Array | Java最短代码实现

Total Accepted: 46230 Total Submissions: 143069 Difficulty: 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.

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.

【抛砖】

该实现是按照快排的思想进行实现,时间复杂度为O(n*logn):

    public int findKthLargest(int[] nums, int k) {
        int leftBoundary = 0;
        int rightBouondary = nums.length - 1;
        while (leftBoundary < rightBouondary) {
            int temp = nums[leftBoundary];
            int left = leftBoundary;
            int right = rightBouondary;
            while (left < right) {
                while (right > left && nums[right] <= temp)
                    right--;
                nums[left] = nums[right];
                while (left < right && nums[left] > temp)
                    left++;
                nums[right] = nums[left];
            }
            nums[left] = temp;
            if (left == k - 1) return nums[left];
            else if (left < k - 1) leftBoundary = left + 1;
            else rightBouondary = left - 1;
        }
        return nums[leftBoundary];
    }
31 / 31  test cases passed. Runtime: 55 ms  Your runtime beats 27.71% of javasubmissions.
欢迎优化!

你可能感兴趣的:(java,LeetCode,array,sort,Quick)