前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >堆-高频题

堆-高频题

原创
作者头像
王脸小
修改2021-08-16 10:33:55
7910
修改2021-08-16 10:33:55
举报
文章被收录于专栏:王漂亮王漂亮

347. 前 K 个高频元素

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.

Solution

class Solution(object):
    def topKFrequent(self, nums, k):
        from collections import Counter
        import heapq
        c = Counter(nums)
        return heapq.nlargest(k, c.keys(), key = c.get)

Solution

from collections import Counter
class Solution:
    def topKFrequent(self, nums, k):
        c = Counter(nums)
        h = []
        res = []
        for v,f in c.items():
            if len(h) < k:
                heapq.heappush(h, (f, v))
            else:
                heapq.heappushpop(h, (f, v))
        for i in range(k):
            res.append(h[i][1])
            
        return res

nlogk

215. 数组中的第K个最大元素

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

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

Solution:

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        if not nums: return 0
        h = []
        
        for i in range(len(nums)):
            if len(h) < k:
                heapq.heappush(h, nums[i])
            else:
                heapq.heappushpop(h, nums[i])
                
        return h[0]

nlogk

Solution - 二分搜索

class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        if k>len(nums): return None
        
        l, r = [], []
        for i in range(1, len(nums)):
            if nums[i] > nums[0]: r.append(nums[i])
            elif nums[i] <= nums[0]: l.append(nums[i])
                
        
        if len(r)+1 == k: return nums[0]
        elif len(r)>=k : return self.findKthLargest(r, k)
        else: return self.findKthLargest(l, k-len(r)-1)
            
        return None

378. 有序矩阵中第K小的元素

Kth Smallest Element in a Sorted Matrix

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

matrix = [
   [ 1,  5,  9],
   [10, 11, 13],
   [12, 13, 15]
],
k = 8,

return 13.

Note: You may assume k is always valid, 1 ≤ k ≤ n2.

Solution:

暴力排序(nlogn) -> 最大堆(nlogk) ->二分法nlogk

klogk: 一次添加右和下,pop出其中较小的,每次pop k-1,pop k次返回

class Solution:
    def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
        row, col = len(matrix), len(matrix[0])
        h = [(matrix[0][0], 0, 0)]
        res = 0
        visited = set((0,0))
        
        while k > 0:
            res, r, c = h.pop()
            if r+1 < row and (r+1,c) not in visited:
                heapq.heappush(h, (matrix[r+1][c], r+1, c))
                visited.add((r+1,c))
            
            if c+1 < col and (r,c+1) not in visited:
                heapq.heappush(h, (matrix[r][c+1], r, c+1))
                visited.add((r,c+1))
    
            k -= 1
            
        return res

nlogk

讲解

计算最大值和最小值的平均值,count_num算出小于该平均值的个数,个数大于小于k决定了left和right的变化(本质上反映了target的变化)

class Solution(object):
    def kthSmallest(self, matrix, k):
        # 计算小于等于目标值的元素个数,根据递增规则,从右上角开始查找
        def count_num(m, target):
            i = 0
            j = len(m) - 1
            ans = 0
            while i < len(m) and j >= 0:
                if m[i][j] <= target:
                    ans += j + 1
                    i += 1
                else:
                    j -= 1
            return ans
        
        #  思路:左上角元素最小,右下角元素最大,计算小于等于中间值的元素个数
        left = matrix[0][0]
        right = matrix[-1][-1]
        # 二分法查找
        while left < right:
            mid = (left + right) >> 1
            # print(' mid = ', mid)
            count = count_num(matrix, mid)
            # print('count = ', count)
            if count < k:
                left = mid + 1
            else:
                right = mid
        return left

218. 天际线问题

The Skyline Problem

A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively (Figure B).

添加描述

The geometric information of each building is represented by a triplet of integers [Li, Ri, Hi], where Li and Ri are the x coordinates of the left and right edge of the ith building, respectively, and Hi is its height. It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height 0.

For instance, the dimensions of all buildings in Figure A are recorded as: [ [2 9 10], [3 7 15], [5 12 12], [15 20 10], [19 24 8] ] .

The output is a list of "key points" (red dots in Figure B) in the format of [ [x1,y1], [x2, y2], [x3, y3], ... ] that uniquely defines a skyline. A key point is the left endpoint of a horizontal line segment. Note that the last key point, where the rightmost building ends, is merely used to mark the termination of the skyline, and always has zero height. Also, the ground in between any two adjacent buildings should be considered part of the skyline contour.

For instance, the skyline in Figure B should be represented as:[ [2 10], [3 15], [7 12], [12 0], [15 10], [20 8], [24, 0] ].

Notes:

  • The number of buildings in any input list is guaranteed to be in the range [0, 10000].
  • The input list is already sorted in ascending order by the left x position Li.
  • The output list must be sorted by the x position.
  • There must be no consecutive horizontal lines of equal height in the output skyline. For instance, [...[2 3], [4 5], [7 5], [11 5], [12 7]...] is not acceptable; the three lines of height 5 should be merged into one in the final output as such: [...[2 3], [4 5], [12 7], ...]

Solution:

ab

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 347. 前 K 个高频元素
  • 215. 数组中的第K个最大元素
  • 378. 有序矩阵中第K小的元素
  • 218. 天际线问题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档