Skip to content

Commit 941b25b

Browse files
authored
Merge pull request neetcode-gh#96 from UnresolvedCold/main
Updates and CPP codes
2 parents f5dbdfd + d7d8386 commit 941b25b

16 files changed

+119
-0
lines changed

cpp/1046-Last-Stone-Weight.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public:
3+
int lastStoneWeight(vector<int>& stones) {
4+
priority_queue<int, vector<int>> pq(stones.begin(), stones.end());
5+
pq.push(0);
6+
7+
while (pq.size()>=1) {
8+
int t1 = pq.top();
9+
pq.pop();
10+
if(pq.empty()) break;
11+
int t2 = pq.top();
12+
pq.pop();
13+
pq.push(abs(t1-t2));
14+
}
15+
16+
return pq.top();
17+
}
18+
};
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
class Solution {
2+
public:
3+
int findKthLargest(vector<int>& nums, int k) {
4+
priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
5+
while (pq.size() > k)pq.pop();
6+
return pq.top();
7+
}
8+
};
File renamed without changes.
File renamed without changes.

cpp/543-Diameter-of-Binary-Tree.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
15+
int MaxHeight(TreeNode* root, int& res) {
16+
if (root == NULL) return 0;
17+
int l = MaxHeight(root->left, res);
18+
int r = MaxHeight(root->right, res);
19+
res = max(res, max(max(l, r), l + r));
20+
return 1 + max(l, r);
21+
}
22+
23+
int diameterOfBinaryTree(TreeNode* root) {
24+
int breadth = 0;
25+
MaxHeight(root, breadth);
26+
return breadth;
27+
}
28+
};
File renamed without changes.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class KthLargest {
2+
public:
3+
priority_queue<int, vector<int>, greater<int>> pq;
4+
int k;
5+
KthLargest(int k, vector<int>& nums) {
6+
this->k = k;
7+
for (auto a: nums) pq.push(a);
8+
while(pq.size()>k){
9+
pq.pop();
10+
}
11+
}
12+
13+
int add(int val) {
14+
pq.push(val);
15+
while(pq.size()>k){
16+
pq.pop();
17+
}
18+
return pq.top();
19+
}
20+
};
21+
22+
/**
23+
* Your KthLargest object will be instantiated and called as such:
24+
* KthLargest* obj = new KthLargest(k, nums);
25+
* int param_1 = obj->add(val);
26+
*/

0 commit comments

Comments
 (0)