题库chevron_right分类chevron_right堆(优先队列)
label

堆(优先队列)

169 道题目
简单: 15中等: 93困难: 61

堆(优先队列) 是技术面试里最常出现的能力维度之一。建议先掌握基础题型的边界处理,再逐步过渡到模式识别和复杂度 trade-off。

面试场景

高频考察问题建模、边界条件与口头表达的清晰度。

常见误区

只背模板不解释为什么,容易在追问里失分。

练习策略

每轮练 3-5 题,固定复盘复杂度和可替代解法。

推荐练习顺序

#题目难度
23

合并 K 个升序链表

Merge k Sorted Lists requires efficiently combining multiple sorted linked lists into one using pointers and priority qu…

困难
215

数组中的第K个最大元素

Find the kth largest element in an unsorted array using optimal approaches like Quickselect or heaps.

中等
218

天际线问题

The Skyline Problem requires calculating a city's silhouette using array manipulation and divide-and-conquer techniques …

困难
239

滑动窗口最大值

Solve the "Sliding Window Maximum" problem using efficient techniques like the sliding window, deque, and priority queue…

困难
264

丑数 II

Find the nth ugly number, where ugly numbers have prime factors limited to 2, 3, and 5.

中等
295

数据流的中位数

Implement a MedianFinder class that supports adding numbers and finding the median from a data stream.

困难
347

前 K 个高频元素

Find the k most frequent elements from an array using efficient algorithms like hashing and sorting.

中等
355

设计推特

Design Twitter requires implementing post, follow, unfollow, and news feed retrieval using linked-list pointer manipulat…

中等
373

查找和最小的 K 对数字

Find K Pairs with Smallest Sums combines arrays and heap usage to select the smallest sum pairs efficiently.

中等
378

有序矩阵中第 K 小的元素

Find the kth smallest element in a sorted n x n matrix using efficient binary search or heap strategies for optimized me…

中等
407

接雨水 II

Solve Trapping Rain Water II using breadth-first search and priority queues for efficient water trapping in a matrix.

困难
420

强密码检验器

The Strong Password Checker problem challenges you to optimize password strength while minimizing steps using greedy alg…

困难
451

根据字符出现频率排序

Sort Characters By Frequency requires counting characters efficiently and rearranging a string in descending frequency o…

中等
480

滑动窗口中位数

Compute the median for each sliding window of size k in an array using efficient array scanning and hash lookup techniqu…

困难
502

IPO

Maximize total capital by selecting up to k projects, based on initial capital and project profits using a greedy strate…

困难
506

相对名次

Solve Relative Ranks by sorting scores with original indices, then writing medal labels or numeric places back in answer…

简单
621

任务调度器

Task Scheduler is solved by counting task frequencies and computing how cooldown gaps force idle slots around the most f…

中等
630

课程表 III

Solve the 'Course Schedule III' problem with a greedy approach involving course selection and validation of constraints.

困难
632

最小区间

Find the minimal range covering at least one number from each of k sorted lists using array scanning and hash lookup eff…

困难
658

找到 K 个最接近的元素

Identify the k integers closest to a target x in a sorted array using binary search and two-pointer strategies efficient…

中等
659

分割数组为连续子序列

Verify if it's possible to split a sorted array into consecutive subsequences of length 3 or more.

中等
675

为高尔夫比赛砍树

Determine the minimum steps to cut all trees in a forest matrix in ascending height order using BFS traversal and priori…

困难
692

前K个高频单词

Solve Top K Frequent Words by counting each word, then ordering ties alphabetically so frequency wins before lexicograph…

中等
703

数据流中的第 K 大元素

Find the kth largest element in a dynamic stream using binary-tree traversal and efficient state tracking with a min-hea…

简单
743

网络延迟时间

Find the minimum time for a signal to travel to all nodes in a directed graph or determine if it's impossible.

中等
767

重构字符串

Reorganize a string so that no two adjacent characters are the same, if possible, using a greedy approach.

中等
778

水位上升的泳池中游泳

Solve the problem of swimming through a grid of rising water with a binary search on the valid answer space.

困难
786

第 K 个最小的质数分数

Find the k-th smallest fraction from a sorted array of unique primes using a binary search over the answer space.

中等
787

K 站中转内最便宜的航班

Find the cheapest flight from a source to a destination with at most K stops using graph traversal techniques efficientl…

中等
855

考场就座

Simulate an exam room where each student chooses a seat maximizing distance to others, using design plus heap structures…

中等
857

雇佣 K 名工人的最低成本

Find the minimum cost to hire exactly k workers based on quality and wage expectations in this challenging greedy proble…

困难
862

和至少为 K 的最短子数组

Find the shortest subarray with a sum of at least k using binary search and sliding window techniques.

困难
871

最低加油次数

Determine the minimum number of refueling stops needed to reach a target using dynamic programming and greedy strategies…

困难
882

细分图中的可到达节点

The Reachable Nodes In Subdivided Graph problem requires efficiently finding the reachable nodes using graph traversal a…

困难
912

排序数组

Sort an array using an optimal algorithm, focusing on time and space complexity considerations.

中等
973

最接近原点的 K 个点

Find the k closest points to the origin in a 2D plane using array operations and Euclidean distance calculations efficie…

中等
1046

最后一块石头的重量

In the 'Last Stone Weight' problem, we smash the two heaviest stones until one remains, using heaps or sorting.

简单
1054

距离相等的条形码

Rearrange barcodes in an array so that no two adjacent elements are equal, using a greedy approach and hash table for ef…

中等
1094

拼车

Determine if a car can handle multiple trips without exceeding its capacity using array sorting and event simulation tec…

中等
1172

餐盘栈

Design a system that manages dinner plate stacks using stack-based state management, handling dynamic plate placement an…

困难
1263

推箱子

Solve the minimum moves to push a box to its target using BFS and priority handling in a grid-based warehouse layout eff…

困难
1268

搜索推荐系统

Design a search suggestion system that provides the top three lexicographically smallest products matching a search word…

中等
1337

矩阵中战斗力最弱的 K 行

Find the k weakest rows in a binary matrix where rows contain soldiers and civilians, using sorting and binary search te…

简单
1338

数组大小减半

This problem asks to minimize the set of integers removed to reduce an array's size to at least half by removing occurre…

中等
1353

最多可以参加的会议数目

Maximize the number of events you can attend given their start and end days using a greedy strategy.

中等
1354

多次求和构造目标数组

This problem requires constructing a target array from an array of ones, using multiple sum operations and a priority qu…

困难
1368

使网格图至少有一条有效路径的最小代价

Determine the minimum cost to create at least one valid path from the top-left to bottom-right in a directional grid.

困难
1383

最大的团队表现值

Maximize the performance of a team by selecting up to k engineers with the highest performance based on speed and effici…

困难
1388

3n 块披萨

Maximize your pizza slice sum from a 3n-sized circular array using state transition dynamic programming efficiently.

困难
1405

最长快乐字符串

Solve the "Longest Happy String" problem using a greedy approach with validation of invariants for constructing the long…

中等
1424

对角线遍历 II

Traverse a jagged 2D array diagonally by grouping elements with equal row and column sums efficiently using sorting and …

中等
1425

带限制的子序列和

Solve the Constrained Subsequence Sum problem using dynamic programming, sliding window, and priority queues to maximize…

困难
1438

绝对差不超过限制的最长连续子数组

Find the longest subarray with elements whose absolute difference is within a specified limit using a sliding window app…

中等
1439

有序矩阵中的第 k 个最小数组和

Find the kth smallest sum in a matrix with sorted rows using binary search and a heap-based approach.

困难
1464

数组中两元素的最大乘积

Find the maximum product of two elements in an array by carefully selecting indices and leveraging sorting for efficienc…

简单
1488

避免洪水泛滥

This problem asks you to avoid flooding by deciding when to dry lakes between rain events.

中等
1499

满足不等式的最大值

Max Value of Equation asks to find the maximum value of a specific equation on a set of 2D points using sliding window t…

困难
1514

概率最大的路径

Find the path with the highest success probability in a graph from a start node to an end node, using edge probabilities…

中等
1606

找到处理最多请求的服务器

Given k servers and a series of requests, find the busiest server(s) using greedy strategies and efficient server tracki…

困难
1631

最小体力消耗路径

Find the minimum effort required to travel from the top-left to the bottom-right of a grid, considering height differenc…

中等
1642

可以到达的最远建筑

Furthest Building You Can Reach explores a greedy approach with heap-based optimization to find the maximum reachable bu…

中等
1648

销售价值减少的颜色球

Maximize total value by greedily selling diminishing-valued colored balls based on inventory and customer orders.

中等
1675

数组的最小偏移量

Given a positive integer array, repeatedly double or halve elements to minimize the difference between its largest and s…

困难
1686

石子游戏 VI

Determine the winner in Stone Game VI using a greedy strategy that accounts for each stone's dual value impact on Alice …

中等
1687

从仓库到码头运输箱子

Optimize the minimum number of trips to deliver boxes to ports under strict ship constraints using dynamic programming t…

困难
1696

跳跃游戏 VI

Jump Game VI challenges you to maximize your score while jumping through an array using state transition dynamic program…

中等
1705

吃苹果的最大数目

Maximize apples eaten by choosing the best apples first, considering their rot days and available days to eat them.

中等
1738

找出第 K 大的异或坐标值

Compute the kth largest XOR coordinate in a 2D matrix using prefix sums, bit manipulation, and optimized selection techn…

中等
1753

移除石子的最大得分

Maximize the score in a solitaire game by optimally removing stones from three piles with a greedy approach.

中等
1776

车队 II

Car Fleet II involves calculating collision times between cars traveling at different speeds along a one-lane road using…

困难
1786

从第一个节点出发到最后一个节点的受限路径数

Solve the problem of finding the number of restricted paths in a weighted undirected graph, leveraging graph algorithms …

中等
1792

最大平均通过率

Maximize the average pass ratio by assigning extra guaranteed-passing students using a greedy heap strategy for optimal …

中等
1801

积压订单中的订单总数

Determine the total number of unfulfilled buy and sell orders using heaps to simulate backlog processing efficiently in …

中等
1825

求出 MK 平均值

Find the MKAverage of a stream of integers using a queue-driven approach with efficient state management.

困难
1834

单线程 CPU

Simulate task processing with a single-threaded CPU by sorting and prioritizing tasks based on arrival and processing ti…

中等
1845

座位预约管理系统

Manage seat reservations efficiently using a design combining priority queue to always return the lowest available seat …

中等
1851

包含每个查询的最小区间

Find the smallest interval containing each query efficiently using binary search.

困难
1878

矩阵中最大的三个菱形和

Find the three largest distinct rhombus sums from a given grid using array and math techniques.

中等
1882

使用服务器处理任务

Assign tasks to servers efficiently using arrays and heaps, resolving ties by weight and index while tracking availabili…

中等
1912

设计电影租借系统

Implement a movie rental system with efficient search, rent, drop, and report operations using arrays and hash lookups.

困难
1942

最小未被占据椅子的编号

Solve The Number of the Smallest Unoccupied Chair by sorting arrivals and managing freed seats before each new assignmen…

中等
1962

移除石子使总数最小

Minimize the total stones by repeatedly removing half from the largest pile using a greedy heap strategy.

中等
1985

找出数组中的第 K 大整数

This problem asks to find the kth largest integer in an array of string numbers, highlighting sorting and string-based c…

中等
2034

股票价格波动

Design an efficient algorithm for managing stock price fluctuations with incorrect and unordered data in a data stream.

中等
2054

两个最好的不重叠活动

Maximize the total value of at most two non-overlapping events using state transition dynamic programming efficiently.

中等
2099

找到和最大的长度为 K 的子序列

Pick the k largest values, then restore their original order to build the maximum-sum subsequence correctly.

简单
2102

序列顺序查询

Track rankings of locations with names and scores, adding new locations and retrieving top-ranked ones efficiently.

困难
2146

价格范围内最高排名的 K 样物品

Use BFS to rank reachable shop items by distance, price, row, and column, then return the best k coordinates.

中等
2163

删除元素后和的最小差值

Minimize the difference between sums after removing n elements from a 3n array by dividing the remaining elements into t…

困难
2182

构造限制重复的字符串

Construct a lexicographically largest string from a given string with no letter appearing more than a repeatLimit times …

中等
2208

将数组和减半的最少操作次数

Minimize operations to halve an array's sum using greedy choices and heap data structures.

中等
2231

按奇偶性交换后的最大数字

Maximize a number by swapping digits of the same parity using sorting and priority queue techniques efficiently.

简单
2233

K 次增加后的最大乘积

Maximize the product of an array after performing up to k increments using a greedy approach with heap optimization.

中等
2285

道路的最大总重要性

Assign unique values to cities to maximize the total importance of all roads using greedy selection based on city connec…

中等
2290

到达角落需要移除障碍物的最小数目

Find the minimum obstacles to remove in a 2D grid to reach the bottom-right corner using BFS graph traversal techniques.

困难
2333

最小差值平方和

Calculate the minimum sum of squared differences between two arrays using limited modifications and binary search techni…

中等
2335

装满杯子需要的最短总时长

Determine the minimum seconds to fill cups of cold, warm, and hot water using a greedy selection strategy and invariant …

简单
2336

无限集中的最小数字

Design a data structure to handle the smallest missing element in an infinite set, with the ability to add and remove el…

中等
2342

数位和相等数对的最大和

Find the maximum sum of two numbers with equal digit sums in a given array of positive integers.

中等
2343

裁剪数字后查询第 K 小的数字

Solve the Query Kth Smallest Trimmed Number problem by efficiently trimming and sorting strings in an array to answer qu…

中等
2344

使数组可以被整除的最少删除次数

Find the minimum number of deletions to make the smallest element in nums divide all elements of numsDivide.

困难
2349

设计数字容器系统

Learn to implement a Number Container System using hash tables and design techniques to efficiently track numbers and in…

中等
2353

设计食物评分系统

Design a food rating system that tracks and updates ratings of foods, finding the highest rated items by cuisine.

中等
2357

使数组中所有元素都等于零

Minimize operations to make all array elements zero by subtracting equal amounts in each operation.

简单
2386

找出数组的第 K 大和

Find the K-Sum of an Array requires computing the kth largest subsequence sum in an array using sorting and heap techniq…

困难
2398

预算内的最多机器人数目

Determine the maximum number of consecutive robots you can operate without exceeding a given budget using efficient bina…

困难
2402

会议室 III

Determine which meeting room holds the most meetings by simulating room assignments with precise time tracking.

困难
2406

将区间分为最少组数

Determine the minimum number of non-overlapping groups for a set of intervals using precise two-pointer scanning logic.

中等
2424

最长上传前缀

Calculate the longest continuous uploaded prefix in a video stream efficiently using a mix of binary search and data str…

中等
2454

下一个更大元素 IV

Find the second greater integer for each element in an array using binary search and monotonic stack techniques.

困难
2456

最流行的视频创作者

Identify the most popular video creator by summing views and selecting their top-viewed video with array and hash patter…

中等
2462

雇佣 K 位工人的总代价

Optimize the total cost of hiring exactly k workers using a two-pointer approach with invariant tracking and priority qu…

中等
2497

图中最大星和

Find the maximum star sum in a graph with specific node values and edges, using greedy algorithms to select the optimal …

中等
2500

删除每行中的最大值

Calculate the total of removed maximum values from each row of a matrix, iterating until all columns are deleted efficie…

简单
2503

矩阵查询可获得的最大分数

Solve the Maximum Number of Points From Grid Queries problem using two-pointer scanning and invariant tracking.

困难
2512

奖励最顶尖的 K 名学生

Calculate top K student scores by scanning reports and using hash tables for positive and negative word lookups efficien…

中等
2530

执行 K 次操作后的最大分数

Maximize your score by applying exactly k operations on an array using greedy selection and heap optimization techniques…

中等
2532

过桥的时间

Time to Cross a Bridge involves simulating worker movements using arrays and heaps to determine when the last worker cro…

困难
2542

最大子序列的分数

Maximize the score of a subsequence by selecting indices based on nums1 and nums2, using a greedy approach and sorting.

中等
2551

将珠子放入背包中

The "Put Marbles in Bags" problem challenges you to distribute marbles into bags for maximum score difference using gree…

困难
2558

从数量最多的堆取走礼物

Take Gifts From the Richest Pile uses a heap to simulate the process of taking gifts from the richest pile over a number…

简单
2577

在网格图中访问一个格子的最少时间

Compute the fastest path in a grid where each cell has a minimum time requirement using BFS and priority queue technique…

困难
2593

标记所有元素后数组的分数

The problem involves marking elements in an array and calculating the score based on adjacent elements.

中等
2611

老鼠和奶酪

In 'Mice and Cheese', you must maximize the total reward of two mice eating cheese while respecting their preferences an…

中等
2617

网格图中最少访问的格子数

Determine the minimum number of cells to visit in a grid using state transition dynamic programming and efficient traver…

困难
2642

设计可以求最短路径的图类

Implement a dynamic weighted directed graph with efficient shortest path queries and edge additions in real time.

困难
2662

前往目标的最小代价

Find the minimum cost path between two points, using special roads or direct moves in a 2D space.

中等
2679

矩阵中的和

Calculate the maximum score by repeatedly removing the largest elements from each row of a 2D matrix efficiently using s…

中等
2699

修改图中的边权

Modify Graph Edge Weights is a graph problem where you adjust edge weights to match a target shortest path distance.

困难
2762

不间断子数组

Count all continuous subarrays efficiently using sliding window with running max-min state tracking for array consistenc…

中等
2812

找出最安全路径

Find the Safest Path in a Grid uses binary search and BFS to maximize path safeness from thieves in a grid.

中等
2813

子序列最大优雅度

Maximize elegance of a k-length subsequence from a list of items with profits and categories.

困难
2931

购买物品的最大开销

Maximize spending by carefully choosing the right items across multiple shops over m * n days.

困难
2940

找到 Alice 和 Bob 可以相遇的建筑

Determine the leftmost building where Alice and Bob can meet using a binary search over valid move sequences.

困难
2944

购买水果需要的最少金币数

Calculate the minimum coins to buy fruits using state transition dynamic programming while handling rewards and purchase…

中等
2959

关闭分部的可行集合数目

Calculate all valid sets of branch closures while keeping remaining branches within maxDistance using bitmask and graph …

困难
2973

树中每个节点放置的金币数目

Determine the exact number of coins to place on each tree node using subtree cost products and DFS tracking.

困难
2974

最小数字游戏

The Minimum Number Game involves simulating moves by Alice and Bob on an array, sorting elements and appending them to a…

简单
3013

将数组分成最小总代价的子数组 II

This problem asks to divide an array into subarrays with a minimal cost and certain constraints on subarray positions.

困难
3049

标记所有下标的最早秒数 II

This problem asks to determine the earliest second at which all indices in an array can be marked using a sequence of op…

困难
3066

超过阈值的最少操作数 II

Calculate the fewest operations to make every array element exceed a threshold using a min-heap simulation strategy effi…

中等
3080

执行操作标记数组中的元素

Efficiently mark elements in an array based on queries using scanning plus hash lookup to track marked indices and compu…

中等
3081

替换字符串中的问号使分数最小

Minimize the cost of a string with '?' characters by replacing them with letters in lexicographical order while minimizi…

中等
3092

最高频率的 ID

Track the most frequent ID after each update in a dynamic collection of IDs with changing frequencies.

中等
3112

访问消失节点的最少时间

Determine the minimum time to visit each node in a disappearing-node graph using arrays, graphs, and priority queues eff…

中等
3123

最短路径中的边

Use two Dijkstra runs to mark exactly which edges can appear on at least one shortest path from 0 to n - 1.

困难
3170

删除星号以后字典序最小的字符串

Find the lexicographically smallest string by removing stars using stack-based state management and careful character se…

中等
3264

K 次乘运算后的最终数组 I

Solve the problem of determining the final state of an array after multiple multiplication operations using a priority q…

简单
3266

K 次乘运算后的最终数组 II

Optimize the final state of an array after performing k multiplication operations with priority queues.

困难
3275

第 K 近障碍物查询

Solve the K-th nearest obstacle query problem using array and heap (priority queue) techniques to find distances efficie…

中等
3286

穿越网格图的安全路径

Determine if you can safely traverse a binary grid from top-left to bottom-right using limited health points.

中等
3296

移山所需的最少秒数

Determine the minimum seconds required to reduce a mountain to zero height using simultaneous workers efficiently.

中等
3318

计算子数组的 x-sum I

Compute the x-sum of every subarray of length k efficiently using array scanning combined with hash lookup techniques.

简单
3321

计算子数组的 x-sum II

Calculate the x-sum for every k-length subarray using efficient array scanning and hash-based counting techniques.

困难
3341

到达最后一个房间的最少时间 I

Find Minimum Time to Reach Last Room I challenges you to determine the minimum time to travel in a dungeon with a grid l…

中等
3342

到达最后一个房间的最少时间 II

Calculate the minimum time to reach the last room in a grid with alternating move times using array and graph patterns.

中等
3362

零数组变换 III

Zero Array Transformation III requires removing the minimum number of queries to make all elements zero using greedy val…

中等
3377

使两个整数相等的数位操作

Transform n into m using allowed digit operations without creating primes, applying math and graph strategies efficientl…

中等
3408

设计任务管理器

Design a Task Manager that can efficiently handle task management operations such as adding, editing, executing, and rem…

中等
3462

提取至多 K 个元素的最大总和

Find the maximum sum by selecting at most k elements from a 2D matrix respecting per-row limits using a greedy strategy.

中等
3478

选出和最大的 K 个元素

Choose K Elements With Maximum Sum involves sorting and selecting elements based on a specific rule, applying array plus…

中等
3505

使 K 个子数组内元素相等的最少操作数

Compute the minimum operations to ensure at least k non-overlapping subarrays of size x have all equal elements efficien…

困难
3507

移除最小数对使数组有序 I

This problem asks for the minimum number of operations to make an array non-decreasing by removing pairs of elements.

简单
3510

移除最小数对使数组有序 II

The problem asks to find the minimum number of operations to make an array non-decreasing by removing pairs of elements.

困难
3572

选择不同 X 值三元组使 Y 值之和最大

Select three distinct x-values from arrays to maximize the sum of their corresponding y-values efficiently using hashing…

中等
3594

所有人渡河所需的最短时间

Find the minimum time to transport individuals across a river with dynamic environmental conditions and boat capacity.

困难
3604

有向图中到达终点的最少时间

The problem involves finding the minimum time to reach the destination in a directed graph with time-dependent edges.

中等
3607

电网维护

Determine which power stations remain connected after maintenance using array scanning and hash lookups to track compone…

中等
3620

恢复网络路径

Find the maximum recovery cost of valid paths in a directed acyclic graph where some nodes are offline.

困难

关联高频模式

LeetCode 堆(优先队列)题型题解:169题训练路线