Skip to content

Commit 088d50a

Browse files
committed
Heap
1 parent ab277e8 commit 088d50a

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

347.TopKFrequent.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// 347. Top K Frequent Elements
2+
3+
// Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.
4+
5+
// Example 1:
6+
7+
// Input: nums = [1,1,1,2,2,3], k = 2
8+
// Output: [1,2]
9+
// Example 2:
10+
11+
// Input: nums = [1], k = 1
12+
// Output: [1]
13+
14+
public class Solution {
15+
public int[] TopKFrequent(int[] nums, int k) {
16+
Dictionary<int,int> map = new Dictionary<int,int>();
17+
foreach(int num in nums){
18+
if(map.ContainsKey(num))
19+
map[num]++;
20+
else
21+
map[num] = 1;
22+
}
23+
PriorityQueue<int,int> minHeap = new PriorityQueue<int,int>();
24+
foreach(var item in map){
25+
minHeap.Enqueue(item.Key,item.Value);
26+
if(minHeap.Count > k)
27+
minHeap.Dequeue();
28+
}
29+
int[] res = new int[k];
30+
int i = 0;
31+
while(minHeap.Count > 0)
32+
res[i++] = minHeap.Dequeue();
33+
return res;
34+
}
35+
}

378.KthSmallest.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// 378. Kth Smallest Element in a Sorted Matrix
2+
3+
// Given an n x n matrix where each of the rows and columns is sorted in ascending order, return the kth smallest element in the matrix.
4+
5+
// Note that it is the kth smallest element in the sorted order, not the kth distinct element.
6+
7+
// You must find a solution with a memory complexity better than O(n2).
8+
9+
// Example 1:
10+
11+
// Input: matrix = [[1,5,9],[10,11,13],[12,13,15]], k = 8
12+
// Output: 13
13+
// Explanation: The elements in the matrix are [1,5,9,10,11,12,13,13,15], and the 8th smallest number is 13
14+
// Example 2:
15+
16+
// Input: matrix = [[-5]], k = 1
17+
// Output: -5
18+
19+
public class Solution {
20+
public int KthSmallest(int[][] matrix, int k) {
21+
PriorityQueue<int,int> maxHeap = new PriorityQueue<int,int>();
22+
int row = matrix.Length;
23+
int col = matrix[0].Length;
24+
for(int i = 0; i < row; i++ ){
25+
for( int j = 0; j < col; j++){
26+
if(maxHeap.Count == k && matrix[i][j] >= maxHeap.Peek() )
27+
break;
28+
maxHeap.Enqueue(matrix[i][j], -1*matrix[i][j]);
29+
if(maxHeap.Count > k){
30+
maxHeap.Dequeue();
31+
}
32+
}
33+
}
34+
return maxHeap.Dequeue();
35+
}
36+
}

0 commit comments

Comments
 (0)