LeetCode----Kth Largest Element in an Array

来源:互联网 发布:中科大软件学院考研 编辑:程序博客网 时间:2024/04/29 02:44

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.

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.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


分析:

寻找数组中第k大的数。思路1:排序。思路2:利用快排的Partition。


代码1:

class Solution(object):    def findKthLargest(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        nums.sort()        return nums[len(nums) - k]


代码2:

class Solution(object):    def findKthLargest(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: int        """        nums_len = len(nums)        l = 1        r = nums_len        while True:            lo, pi, hi = self.partition(nums, l, r)            nums = lo + [pi] + hi            if nums_len - k == len(lo):                return pi            if nums_len - k > len(lo):                l = len(lo) + 2            else:                r = len(lo)    def partition(self, nums, l, r):  # 从第l个元素到第r个元素之间切割        left = nums[:l - 1]        right = nums[r:]        pi, seq = nums[l - 1], nums[l:r]        lo = [x for x in seq if x <= pi]        hi = [x for x in seq if x > pi]        return left + lo, pi, hi + right


0 0