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))


 

发布了249 篇原创文章 · 获赞 102 · 访问量 49万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览