File tree 3 files changed +83
-10
lines changed
solution/1000-1099/1046.Last Stone Weight
3 files changed +83
-10
lines changed Original file line number Diff line number Diff line change 58
58
<!-- 这里可写当前语言的特殊实现逻辑 -->
59
59
60
60
``` 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
+ }
66
77
```
67
78
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
+ };
68
97
```
69
98
70
99
<!-- tabs:end -->
Original file line number Diff line number Diff line change @@ -58,13 +58,42 @@ we combine 1 and 1 to get 0 so the array converts to [1] then that's the val
58
58
### ** Java**
59
59
60
60
``` 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
+ }
66
77
```
67
78
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
+ };
68
97
```
69
98
70
99
<!-- tabs:end -->
Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments