LeetCode 347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

----------------------------------------------------------------------------------------------------------------

这本来是个套路问题,但是写了一个大bug,把拿pivot写到while去了,这就不是二分,引以为戒。

class Solution:
    def selectK(self, lst, k, left, right):
        i, j = left, right
        mid = ((j - i) >> 1) + i
        pivot = lst[mid][0]

        while (i <= j):
            while (lst[i][0] < pivot):
                i += 1
            while (lst[j][0] > pivot):
                j -= 1
            if (i <= j):
                lst[i], lst[j] = lst[j], lst[i]
                i, j = i + 1, j - 1
        if (i - 1 == j + 1 and i - left == k and lst[i-1][0] == pivot):
            return i - 1
        elif (i - left < k):
            return self.selectK(lst, k-(i-left), i, right)
        else:
            return self.selectK(lst, k, left, i - 1)

    def topKFrequent(self, nums, k):
        d = {}
        for num in nums:
            cur = d[num] if num in d else 0
            d[num] = cur + 1

        lst = []
        for kk, vv in d.items():
            lst.append((vv, kk))  # freq,val
        lst = [(1, 5), (2, 3), (4, 1), (1, 73)]
        l = len(lst)
        kth = self.selectK(lst, l + 1 - k, 0, l - 1)
        res = [item[1] for item in lst[kth:]]
        return res

s = Solution()
print(s.topKFrequent([5,3,1,1,1,3,73,1],1))


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值