Skip to content

Commit ff28360

Browse files
authored
feat: add cpp solution to lc problem: No.1046 (#789)
No.1046.Last Stone Weight
1 parent b20aa66 commit ff28360

File tree

3 files changed

+83
-10
lines changed

3 files changed

+83
-10
lines changed

solution/1000-1099/1046.Last Stone Weight/README.md

+34-5
Original file line numberDiff line numberDiff line change
@@ -58,13 +58,42 @@
5858
<!-- 这里可写当前语言的特殊实现逻辑 -->
5959

6060
```java
61-
62-
```
63-
64-
### **...**
65-
61+
class Solution {
62+
public int lastStoneWeight(int[] stones) {
63+
Queue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
64+
for (int stone : stones) {
65+
queue.offer(stone);
66+
}
67+
while (queue.size() > 1) {
68+
int x = queue.poll();
69+
int y = queue.poll();
70+
if (x != y) {
71+
queue.offer(x - y);
72+
}
73+
}
74+
return queue.isEmpty() ? 0 : queue.poll();
75+
}
76+
}
6677
```
6778

79+
### **C++**
80+
81+
```cpp
82+
class Solution {
83+
public:
84+
int lastStoneWeight(vector<int>& stones) {
85+
priority_queue<int> pq(stones.begin(), stones.end());
86+
while (pq.size() > 1) {
87+
int x = pq.top();
88+
pq.pop();
89+
int y = pq.top();
90+
pq.pop();
91+
if (x != y)
92+
pq.push(x-y);
93+
}
94+
return pq.empty() ? 0 : pq.top();
95+
}
96+
};
6897
```
6998
7099
<!-- tabs:end -->

solution/1000-1099/1046.Last Stone Weight/README_EN.md

+34-5
Original file line numberDiff line numberDiff line change
@@ -58,13 +58,42 @@ we combine 1 and 1 to get 0 so the array converts to [1] then that&#39;s the val
5858
### **Java**
5959

6060
```java
61-
62-
```
63-
64-
### **...**
65-
61+
class Solution {
62+
public int lastStoneWeight(int[] stones) {
63+
Queue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
64+
for (int stone : stones) {
65+
queue.offer(stone);
66+
}
67+
while (queue.size() > 1) {
68+
int x = queue.poll();
69+
int y = queue.poll();
70+
if (x != y) {
71+
queue.offer(x - y);
72+
}
73+
}
74+
return queue.isEmpty() ? 0 : queue.poll();
75+
}
76+
}
6677
```
6778

79+
### **C++**
80+
81+
```cpp
82+
class Solution {
83+
public:
84+
int lastStoneWeight(vector<int>& stones) {
85+
priority_queue<int> pq(stones.begin(), stones.end());
86+
while (pq.size() > 1) {
87+
int x = pq.top();
88+
pq.pop();
89+
int y = pq.top();
90+
pq.pop();
91+
if (x != y)
92+
pq.push(x-y);
93+
}
94+
return pq.empty() ? 0 : pq.top();
95+
}
96+
};
6897
```
6998
7099
<!-- tabs:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public:
3+
int lastStoneWeight(vector<int>& stones) {
4+
priority_queue<int> pq(stones.begin(), stones.end());
5+
while (pq.size() > 1) {
6+
int x = pq.top();
7+
pq.pop();
8+
int y = pq.top();
9+
pq.pop();
10+
if (x != y)
11+
pq.push(x-y);
12+
}
13+
return pq.empty() ? 0 : pq.top();
14+
}
15+
};

0 commit comments

Comments
 (0)