【LeetCode】堆 heap(共31题)

【23】 Merge k Sorted Lists

【215】 Kth Largest Element in an Array (无序数组中最小/大的K个数)

给了一个无序数组,可能有重复数字,找到第 k 个最大的元素并且返回这个元素值。

题解:直接用直接用个堆保存数组中最大的 K 个数。时间复杂度是 O(NlogK)。

 1 //时间复杂度是 O(NlogK), 用堆辅助。
 2 class Solution {
 3 public:
 4     int findKthLargest(vector<int>& nums, int k) {
 5         const int n = nums.size();
 6         priority_queue<int, vector<int>, greater<int>> pq;
 7         for (int i = 0; i < n; ++i) {
 8             if (pq.size() < k) {
 9                 pq.push(nums[i]);
10             } else {
11                 if (pq.top() < nums[i]) {
12                     pq.pop();
13                     pq.push(nums[i]);
14                 }
15             }
16         }
17         return pq.top();
18     }
19 };
View Code

本题可以有 O(N) 的解法,详见《剑指offer》或者《程序员代码面试指南》P336

【218】 The Skyline Problem

【239】 Sliding Window Maximum

【253】 Meeting Rooms II

【264】 Ugly Number II

【295】 Find Median from Data Stream

【313】 Super Ugly Number

【347】 Top K Frequent Elements

【355】 Design Twitter

【358】 Rearrange String k Distance Apart

【373】 Find K Pairs with Smallest Sums

【378】 Kth Smallest Element in a Sorted Matrix

【407】 Trapping Rain Water II

【451】 Sort Characters By Frequency

【502】 IPO

【659】 Split Array into Consecutive Subsequences

【692】 Top K Frequent Words

【703】 Kth Largest Element in a Stream

给个数字流,总是返回最大的第K个元素

解法就是用一个只有K个元素的堆,维护这这些数字里面从最大的第K个到最大的元素。

[最小元素...第K大的元素..最大元素], 这个堆总维护后半段的K个

View Code

【719】 Find K-th Smallest Pair Distance

【743】 Network Delay Time

【759】 Employee Free Time

【767】 Reorganize String

【778】 Swim in Rising Water

【786】 K-th Smallest Prime Fraction

【787】 Cheapest Flights Within K Stops

【818】 Race Car

【857】 Minimum Cost to Hire K Workers

【864】 Shortest Path to Get All Keys

【871】 Minimum Number of Refueling Stops

【882】 Reachable Nodes In Subdivided Graph

猜你喜欢

转载自www.cnblogs.com/zhangwanying/p/9357141.html