Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >堆-高频题

堆-高频题

原创
作者头像
王脸小
修改于 2021-08-16 02:33:55
修改于 2021-08-16 02:33:55
85900
代码可运行
举报
文章被收录于专栏:王漂亮王漂亮
运行总次数:0
代码可运行

347. 前 K 个高频元素

Top K Frequent Elements

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

Example 1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: [3,2,1,5,6,4] and k = 2
Output: 5

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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 - 二分搜索

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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次返回

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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的变化)

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
ab

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

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

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

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
重中之重的二分查找
There are two sorted arrays nums1 and nums2 of size m and n respectively.
王脸小
2020/07/28
5010
Python3刷题系列(八)
哈希表、栈、链表、多数投票、回文、堆、双指针、进制转换 目录: 1,Leetcode-242 2,Leetcode-232 3,Leetcode-160 4,Leetcode-260 5,Leetcode-169 6,Leetcode-409 7,Leetcode-378 8,Leetcode-462 9,Leetcode-504 1,Leetcode-242: # leetcode-242:哈希表 class Solution: # 利用数组实现,战胜了57.81% def isAnagram(
用户5473628
2019/08/08
4820
Leetcode【347、378、451、692】
一般情况下,求前 k 个元素的题目可以使用堆求解。但是如果先进行堆排序(O(n*logn)),再输出前 k 个元素,这样时间复杂度和普通排序方法 sorted() 没有区别。
echobingo
2019/07/01
6080
LeetCode 题目解答——155~226 题
[Updated on 9/22/2017] 如今回头看来,里面很多做法都不是最佳的,有的从复杂度上根本就不是最优解,有的写的太啰嗦,有的则用了一些过于 tricky 的方法。我没有为了这个再更新,就让它们去吧。
四火
2022/07/19
7110
LeetCode 题目解答——155~226 题
多种解法破中等题
0.说在前面1.数组中的第K个最大元素1.0 问题1.1 降序方法1.2 递归快排1.3 非递归快排1.4 最大堆排序1.5 最小堆排序2.二叉搜索树中第K小的元素2.0 问题2.1 递归中序遍历2.2 非递归中序遍历
公众号guangcity
2019/09/20
4300
多种解法破中等题
回溯/贪心高频题
"有关递归的算法,都离不开“树”的遍历这一抽象模型。只不过对于不同的算法,在前(中)后序遍历的时候,所做的事不同而已。 "
王脸小
2019/10/28
1.4K0
Data Structures and Algorithms Basics(010):Heap
# 第一部分、创建堆 # 1,python自建堆: class PriorityQueueBase: """Abstract base class for a priority queue.""" class Item: """Lightweight composite to store priority queue items.""" __slots__ = '_key' , '_value' def __init__ (self,
用户5473628
2019/08/08
4660
3道线段树题
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).
王脸小
2019/11/03
6800
如醉如痴之最小堆
一道简单的题,可以让你如醉如痴,更是因为这一道题,你才会学会很多,不要小看简单,简单中蕴含深意。
公众号guangcity
2019/09/20
3900
如醉如痴之最小堆
Python3刷题系列(七)
https://leetcode.com/problems/different-ways-to-add-parentheses/
用户5473628
2019/08/08
3310
Python堆排序之heapq
heapq模块实现了Python中的堆排序,并提供了有关方法。让用Python实现排序算法有了简单快捷的方式。
小歪
2018/12/24
1.2K0
米哈游(原神)终面算法原题
在房地产行业的上升周期中,房企普遍的高杠杆率和过度扩张如今成为一种"回旋镖",对各个层面都产生了影响。
宫水三叶的刷题日记
2024/02/06
4740
米哈游(原神)终面算法原题
LeetCode笔记:Weekly Contest 284
这一题我的思路很暴力,直接暴力检索一下,找到所有的目标位置,然后加入其对应范围内的所有index即可。
codename_cys
2022/04/13
2040
LeetCode 题目解答—— 第 372 到 415 题
【题目】Your task is to calculate ab mod 1337 where a is a positive integer and b is an extremely large positive integer given in the form of an array.
四火
2022/07/19
8090
LeetCode 题目解答—— 第 372 到 415 题
Data Structures and Algorithms Basics(005):Divid conquer
在计算机科学中,分治法是一种很重要的算法。字面上的解释是“分而治之”,就是把一个复杂的问题分成两个或更多的相同或相似的子问题,再把子问题分成更小的子问题……直到最后子问题可以简单的直接求解,原问题的解即子问题的解的合并。这个技巧是很多高效算法的基础,如二分搜索,排序算法(快速排序,归并排序),傅立叶变换(快速傅立叶变换)......
用户5473628
2019/08/08
5450
【面试高频题】难度 2/5,超常规多语言多解法笔试题
这是 LeetCode 上的 「373. 查找和最小的K对数字」 ,难度为 「中等」。
宫水三叶的刷题日记
2022/11/01
2990
LeetCode 题目解答——第 227 到 310 题
[Updated on 9/22/2017] 如今回头看来,里面很多做法都不是最佳的,有的从复杂度上根本就不是最优解,有的写的太啰嗦,有的则用了一些过于 tricky 的方法。我没有为了这个再更新,就让它们去吧。
四火
2022/07/19
1.2K0
LeetCode 题目解答——第 227 到 310 题
求前 K 个高频元素和队列有啥关系
https://leetcode-cn.com/problems/top-k-frequent-elements/
代码随想录
2021/07/16
7000
LeetCode笔记:Weekly Contest 212 比赛记录
这一次的比赛整体还算OK,虽然最后一题还是没能搞定,但终究也算是一次触底反弹吧,搞定了三题,国内排名165,世界排名520,算是一个比较满意的成绩了。
codename_cys
2021/03/26
2540
LeetCode笔记:Weekly Contest 318
这一题思路上很简单,就是用一个for循环按照题意逐一操作一下,然后重新排个序即可。
codename_cys
2022/11/16
4180
相关推荐
重中之重的二分查找
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验