43
43
44
44
<!-- 这里可写通用的实现逻辑 -->
45
45
46
+ ** 方法一:大根堆(优先队列)**
47
+
48
+ 将 ` stones ` 数组所有元素放入大根堆,执行循环操作,每次弹出两个元素 ` x ` 和 ` y ` ,如果 ` x != y ` ,将 ` x - y ` 放入大根堆。当堆元素个数小于 ` 2 ` 时,退出循环。
49
+
50
+ 最后如果存在堆顶元素,则将其返回,否则返回 ` 0 ` 。
51
+
52
+ 时间复杂度 $O(n\log n)$,空间复杂度 $O(n)$。其中 $n$ 是 ` stones ` 数组的长度。
53
+
46
54
<!-- tabs:start -->
47
55
48
56
### ** Python3**
52
60
``` python
53
61
class Solution :
54
62
def lastStoneWeight (self , stones : List[int ]) -> int :
55
- h = [- s for s in stones]
63
+ h = [- v for v in stones]
56
64
heapify(h)
57
65
while len (h) > 1 :
58
- y, x = - heappop(h), - heappop(h)
66
+ x = heappop(h)
67
+ y = heappop(h)
59
68
if x != y:
60
69
heappush(h, x - y)
61
- return 0 if not h else - h[0 ]
70
+ return 0 if len (h) == 0 else - h[0 ]
62
71
```
63
72
64
73
### ** Java**
@@ -68,18 +77,18 @@ class Solution:
68
77
``` java
69
78
class Solution {
70
79
public int lastStoneWeight (int [] stones ) {
71
- Queue <Integer > queue = new PriorityQueue<> (Comparator . reverseOrder() );
72
- for (int stone : stones) {
73
- queue . offer(stone );
80
+ PriorityQueue <Integer > q = new PriorityQueue<> ((a, b) - > b - a );
81
+ for (int v : stones) {
82
+ q . offer(v );
74
83
}
75
- while (queue . size() > 1 ) {
76
- int x = queue . poll();
77
- int y = queue . poll();
84
+ while (q . size() > 1 ) {
85
+ int y = q . poll();
86
+ int x = q . poll();
78
87
if (x != y) {
79
- queue . offer(x - y );
88
+ q . offer(y - x );
80
89
}
81
90
}
82
- return queue . isEmpty() ? 0 : queue . poll();
91
+ return q . isEmpty() ? 0 : q . poll();
83
92
}
84
93
}
85
94
```
@@ -92,12 +101,9 @@ public:
92
101
int lastStoneWeight(vector<int >& stones) {
93
102
priority_queue<int > pq(stones.begin(), stones.end());
94
103
while (pq.size() > 1) {
95
- int x = pq.top();
96
- pq.pop();
97
- int y = pq.top();
98
- pq.pop();
99
- if (x != y)
100
- pq.push(x - y);
104
+ int x = pq.top(); pq.pop();
105
+ int y = pq.top(); pq.pop();
106
+ if (x != y) pq.push(x - y);
101
107
}
102
108
return pq.empty() ? 0 : pq.top();
103
109
}
@@ -136,6 +142,29 @@ func (h *hp) push(v int) { heap.Push(h, v) }
136
142
func (h *hp) pop() int { return heap.Pop(h).(int) }
137
143
```
138
144
145
+ ### ** JavaScript**
146
+
147
+ ``` js
148
+ /**
149
+ * @param {number[]} stones
150
+ * @return {number}
151
+ */
152
+ var lastStoneWeight = function (stones ) {
153
+ const pq = new MaxPriorityQueue ();
154
+ for (const v of stones) {
155
+ pq .enqueue (v);
156
+ }
157
+ while (pq .size () > 1 ) {
158
+ const x = pq .dequeue ()[' priority' ];
159
+ const y = pq .dequeue ()[' priority' ];
160
+ if (x != y) {
161
+ pq .enqueue (x - y);
162
+ }
163
+ }
164
+ return pq .isEmpty () ? 0 : pq .dequeue ()[' priority' ];
165
+ };
166
+ ```
167
+
139
168
### ** ...**
140
169
141
170
```
0 commit comments