Leetcode-215題: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.

思路

利用快速排序的思想,用數組頭將數組兩分,左邊比它小,右邊比它大。如果這個元素正好是第k個,直接返回;如果比k大,則從比它小的那些數中找出第k大的;否則,從比它大的數中找出相應的數字。

代碼

class Solution(object):

    def quick_sort(self, nums, k):
        i = 0
        for j in range(1,len(nums)):
            if nums[j] > nums[0]:
                i += 1
                nums[i],nums[j] = nums[j],nums[i]
        nums[i],nums[0] = nums[0],nums[i]
        if i == k-1:
            return nums[i]
        elif i > k-1:
            return self.quick_sort(nums[:i], k)
        else:
            return self.quick_sort(nums[i+1:], k-i-1)

    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        if nums==None or len(nums)==0 or k<1:
            return -1
        return self.quick_sort(nums, k)
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容