8.6 练手 腾讯50题

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.

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

 

不太懂这个题目的意思,我的解法是直接数组排序然后输出第k位的数,代码如下:

class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        temp = sorted(nums, reverse = True)
        return temp[k-1]

beat 90%+

去看了一下Discussion ,发现果然是自己想法太简单不适合工程了

如果数组size很小,直接sort,如果数组非常大,那么时间复杂度为O(nlogn)的算法就不太好了。

同时,虽然Accepted了,我还是要需要检测一下nums数组中的元素是否为0个或者不存在,即

if (nums == null || nums.length == 0) return Integer.MAX_VALUE;

解法一: 使用MaxHeap&MinHeap

是Python语言写的使用MinHeap 和 MaxHeap的两种解法较为清晰的解析,还有比较两种堆实现的时间复杂度和空间复杂度对比。

https://leetcode.com/problems/kth-largest-element-in-an-array/discuss/301338/Python-or-tm-215

备注:float('inf')是获取正无穷

解法二:分治思想 Quick Select

较为elegant的代码

想法:

1.选定一个数值作为pivot,进行快排

2.通过快排重整数组使得pivot前的数大,pivot后的数小,同时返回pivot的位置

3.通过得到pivot的位置和k-1比较,如果刚好返回pivot值,如果k-1小则寻找(left,pivot.pos-1)位置,如果k-1大则寻找(pivot.pos+1,right)的位置.

 

def findKthLargest(self, nums, k):
    return self.quickSelect(nums, 0, len(nums)-1, k)

def quickSelect(self, nums, start, n, k): # quick select
    pos = self.partition(nums, start, n)
    if pos == k-1:
        return nums[pos]
    elif pos >= k:
        return self.quickSelect(nums, start, pos - 1, k)
    return self.quickSelect(nums, pos + 1, n, k)
    
def partition(self, nums, left, right):
    pivot = nums[right] # pick the last one as pivot
    i = left
    for j in xrange(left, right): # left to right -1
        if nums[j] > pivot: # the larger elements are in left side
            nums[j], nums[i] = nums[i], nums[j]
            i += 1
    nums[right], nums[i] = nums[i], nums[right] # swap the i and the last element
    return i

这个思想挺好的讲解和拓展:

https://www.cnblogs.com/grandyang/p/4539757.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值