算法设计与分析:Kth Largest Element in an Array(Week 2)

学号:16340008


Question:

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.

Example 1:

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.


Answer:

挑选了分治算法中比较典型的题目研究。题目是寻找一列数组中第k大的数。

一开始的主要思路是在函数中定义三个空列表,遍历数组分别将小于,等于,大于数组第一位的数放进三个空列表中。

然后再递归,根据列表长度和k值的比较对其中一个列表调用函数自身。

以下为第一次完成的代码。

class Solution:
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        list1 = []
        list2 = []
        list3 = []
        for num in nums:
            if num > nums[0]:
                list1.append(num)
            elif num == nums[0]:
                list2.append(num)
            else: 
                list3.append(num)
        if k <= len(list1):
            return self.findKthLargest(list1, k)
        elif k <= len(list1) + len(list2):
            return nums[0]
        else:
            return self.findKthLargest(list3, k - len(list1) - len(list2))

test = Solution()
nums = [3,2,3,1,2,4,5,5,6]
k = 4
print(test.findKthLargest(nums, k))

然而第一次提交得到的runtime为3640 ms,并不理想。

之后尝试不分配新的内存,即原地分段,利用快排的思路实现。

class Solution:
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        left = 0
        right = len(nums) - 1
        while True:
            mid = self.split(nums, left, right)
            if mid == k - 1:
                return nums[mid]
            elif mid > k - 1:
                right = mid - 1
            else:
                left = mid + 1
        
    def split(self, nums, left, right):
        pivot = nums[left]
        i = left + 1
        j = right
        while i <= j:
            if nums[i] < pivot and nums[j] > pivot :
                nums[i], nums[j] = nums[j], nums[i]
                i += 1
                j -= 1
            if nums[i] >= pivot:
                i += 1
            if nums[j] <= pivot:
                j -= 1
        nums[left], nums[j] = nums[j], nums[left]
        return j


test = Solution()
nums = [3,2,3,1,2,4,5,5,6]
k = 4
print(test.findKthLargest(nums, k))

这次Runtime为2488ms,稍有提升。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值