215. Kth Largest Element in an Array

来源:互联网 发布:淘宝花呗怎么开通 编辑:程序博客网 时间:2024/06/03 21:02

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.

java

使用可快排的方式,但是应该还有更好地解决方法,稍后更新

class Solution {    public int findKthLargest(int[] nums, int k) {        if (nums == null || nums.length == 0 || k < 0) {            return -1;        }        if (k > nums.length) {            return -1;        }        quickSort(nums, 0, nums.length - 1);        return nums[nums.length - k];    }    private void quickSort(int[] nums, int start, int end) {        if (start >= end) {            return;        }        int left = start;        int right = end;        int pivot = nums[(left + right) / 2];        while (left <= right) {            while (left <= right && nums[left] < pivot) {                left++;            }            while (left <= right && nums[right] > pivot) {                right--;            }            if (left <= right) {                int temp = nums[left];                nums[left] = nums[right];                nums[right] = temp;                left++;                right--;            }        }        quickSort(nums, start, right);        quickSort(nums, left, end);    }}

python
class Solution(object):    def findKthLargest(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        if nums == None or len(nums) == 0 or k < 0:            return -1        if k > len(nums):            return -1        self.quickSort(nums, 0, len(nums) - 1)        return nums[len(nums) - k]            def quickSort(self, nums, start, end):        if start >= end:            return        left, right = start, end        pivot = nums[(left + right) / 2]        while left <= right:            while left <= right and nums[left] < pivot:                left += 1            while left <= right and nums[right] > pivot:                right -= 1            if left <= right:                nums[left], nums[right] = nums[right], nums[left]                left += 1                right -= 1        self.quickSort(nums, start, right)        self.quickSort(nums, left, end)                        


原创粉丝点击