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 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
一文说清楚ThreadLocal
当多个线程对同一变量进行写操作的时候,容易出现线程安全问题,所以就会用到对应的锁和其他一些方法,我们先不介绍锁,先介绍ThreadLocal, ThreadLocal字面意思本地线程,ThreadLocal使每个线程之间是隔离的,数据是独立的,我们使用过session都知道 session是一个会话,我们可以用它来存储一些用户的基本信息,这样每个用户在服务端都能取到,ThreadLocal也可以做到,ThreadLocal将相应的信息存储在当前的线程中,只有当前线程能够访问,其他线程不能访问,这样就能保证线程安全,其实ThreadLocal是一个定制化的Map。
小四的技术之旅
2022/07/26
3280
面试|再次讲解Threadlocal使用及其内存溢出
浪尖整理本文主要是想帮助大家完全消化面试中常见的ThreadLocal问题。希望读懂此文以后大家可以掌握(没耐心的可以直接阅读底部总结):
Spark学习技巧
2019/07/09
9330
面试|再次讲解Threadlocal使用及其内存溢出
ThreadLocal 源码解读
首先我们看到的是 Thread 中有一个属性 threadLocals,它的类型是 ThreadLocalMap,封装类型是 default(表示它只能在包内可见),jdk 是这么介绍它的:与此线程有关的 ThreadLocal 值,该映射由 ThreadLocal 类维护。 啥意思呢?那就来看看 ThreadLocalMap 是啥玩意!
JMCui
2019/12/11
3230
面试Threadlocal源码解析
今天我们讲一下高频面试题,Threadlocal,他是JDK1.2就已经有了,他是为每一个使用该变量的线程提供独立的副本,可以做到线程间的数据隔离,每一个线程都可以访问各自内部的副本变量。
小土豆Yuki
2020/06/15
2660
深入理解Threadlocal的实现原理
文章开头我想说,这是一篇面向不怎么懂  Threadlocal 的朋友的博客,所以有的人会觉得有点啰嗦,但不论您水平高低,相信耐着性子看完也一定会有收获。
矿泉水
2018/05/11
8823
<一>深入理解Threadlocal的实现原理
文章开头我想说,这是一篇面向不怎么懂  Threadlocal 的朋友的博客,所以有的人会觉得有点啰嗦,但不论您水平高低,相信耐着性子看完也一定会有收获。
用户2141593
2019/02/20
1.7K0
ThreadLocal (中) 原理具体实现详解
由该图可知,Thread类中有一个threadLocals和一个inheritableThreadLocals,它们都是ThreadLocalMap类型的变量,而ThreadLocalMap是一个定制化的HashMap。在默认情况下,每个线程中的这两个变量都为null,只有当线程第一次调用ThreadLocal的set()或get()方法时才华创建它们。其实每个线程的本地变量不是存放在ThreadLocal实例里面,而是存放在具体线程内存空间中。ThreadLocal就是一个工具壳,它通过set方法把value值放入调用线程的threadLocals里面并存放起来,当调用线程调用它的get方法时,再从当前线程的threadLocals变量里面将其拿出来使用。如果调用线程一直不重质,那么这个本地变量会一直存放在调用线程的threadLocals变量里面,所以当不需要使用本地变量的时候可以通过调用ThreadLocal变量的remove()方法,从当前线程的threadLocals里面删除该本地变量。另外,Thread里面的threadLocals为何被设计为map结构?很明显是因为每个线程可以惯量多个ThreadLocal变量。
YanL
2020/04/26
7040
ThreadLocal (中) 原理具体实现详解
为什么 ThreadLocal 可以做到线程隔离?
对于 ThreadLocal 我们都不陌生,它的作用如同它的名字——用于存放「线程本地」变量。
刘水镜
2022/07/29
3000
ThreadLocal及InheritableThreadLocal的原理剖析
我们知道,线程的不安全问题,主要是由于多线程并发读取一个变量而引起的,那么有没有一种办法可以让一个变量是线程独有的呢,这样不就可以解决线程安全问题了么。其实JDK已经为我们提供了ThreadLocal这个东西。
Java学习录
2019/04/18
5910
ThreadLocal 源码解析
ThreadLocal 顾名思义就是在每个线程内部都会存储只有当前线程才能访问的变量的一个副本,然后当前线程修改了该副本的值后而不会影响其他线程的值,各个变量之间相互不影响。
Java技术编程
2020/05/25
3950
ThreadLocal 类
ThreadLocal 并不是一个Thread,而是 ThreadLocalVariable(线程局部变量)。也许把它命名为 ThreadLocalVar更加合适。线程局部变量就是为每一个使用该变量的线程都提供一个变量值的副本,是 Java中一种较为特殊的线程绑定机制,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。ThreadLocal是除了加锁这种同步方式之外的另一种保证多线程访问出现线程不安全的方式。
Java架构师必看
2021/05/14
5150
ThreadLocal 类
ThreadLocal分析
ThreadLocal是一个本地线程副本变量工具类。主要用于将私有线程和该线程存放的副本对象做一个映射,各个线程之间的变量互不干扰,在高并发场景下,可以实现无状态的调用,特别适用于各个线程依赖不通的变量值完成操作的场景。
爱撸猫的杰
2019/08/07
7810
ThreadLocal分析
抛出这8个问题,检验一下你到底会不会ThreadLocal,来摸个底~
ThreadLocal类是用来提供线程内部的局部变量。让这些变量在多线程环境下访问(get/set)时能保证各个线程里的变量相对独立于其他线程内的变量。
Java编程指南
2020/07/24
7420
抛出这8个问题,检验一下你到底会不会ThreadLocal,来摸个底~
java并发之无同步方案-ThreadLocal
1.ThreadLocal  介绍2.ThreadLocal  应用3.ThreadLocal  源码解析3.1解决 Hash 冲突4.ThreadLocal 特性5.4.ThreadLocal 内存泄露问题
Java宝典
2020/11/30
4080
ThreadLocal用法及原理
Synchronized用于线程间的数据共享,而ThreadLocal则用于线程间的数据隔离。
烂猪皮
2019/04/26
1.6K0
聊一聊线程变量绑定之ThreadLocal
这里我们从源码角度来聊一聊 ThreadLocal 的原理。先来看一看它的属性和方法:
山行AI
2019/12/19
9620
聊一聊线程变量绑定之ThreadLocal
ThreadLocal的使用及原理分析
ThreadLocal称作线程本地存储。简单来说,就是ThreadLocal为共享变量在每个线程中都创建一个副本,每个线程可以访问自己内部的副本变量。这样做的好处是可以保证共享变量在多线程环境下访问的线程安全性。
日薪月亿
2019/05/14
5750
ThreadLocal的使用及原理分析
精通高并发与多线程,却不会用ThreadLocal?
之前我们有在并发系列中提到 ThreadLocal 类和基本使用方法,那我们就来看下 ThreadLocal 究竟是如何使用的!
蔡不菜丶
2020/11/11
5160
ThreadLocal原理探究
多线程访问同一个共享变量特别容易出现并发问题,特别是多个线程需要对一个共享变量进行写入时候,为了保证线程安全,一般需要使用者在访问共享变量的时候进行适当的同步,如下图:
加多
2018/09/06
4190
ThreadLocal原理探究
探索JAVA并发 - ThreadLocal
SimpleDateFormat是我们常用的日期格式化工具,但熟悉的朋友都知道它是线程不安全的。
acupt
2019/08/26
4200
相关推荐
一文说清楚ThreadLocal
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验