while (q.size() > 1) { int a = q.top(); q.pop(); int b = q.top(); q.pop(); if (a > b) { q.push(a - b); } } return q.empty() ? 0 : q.top(); } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { publicintlastStoneWeight(int[] stones) { PriorityQueue<Integer> pq = newPriorityQueue<Integer>((a, b) -> b - a); for (int stone : stones) { pq.offer(stone); }
while (pq.size() > 1) { inta= pq.poll(); intb= pq.poll(); if (a > b) { pq.offer(a - b); } } return pq.isEmpty() ? 0 : pq.poll(); } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var lastStoneWeight = function(stones) { const pq = newMaxPriorityQueue(); for (const stone of stones) { pq.enqueue('x', stone); } while (pq.size() > 1) { const a = pq.dequeue()['priority']; const b = pq.dequeue()['priority']; if (a > b) { pq.enqueue('x', a - b); } } return pq.isEmpty() ? 0 : pq.dequeue()['priority']; };
voidswap(int *a, int *b) { int tmp = *a; *a = *b, *b = tmp; }
voidpush(int *heap, int *heapSize, int x) { heap[++(*heapSize)] = x; for (int i = (*heapSize); i > 1 && heap[i] > heap[i >> 1]; i >>= 1) { swap(&heap[i], &heap[i >> 1]); } }
voidpop(int *heap, int *heapSize) { int tmp = heap[1] = heap[(*heapSize)--]; int i = 1, j = 2; while (j <= (*heapSize)) { if (j != (*heapSize) && heap[j + 1] > heap[j]) ++j; if (heap[j] > tmp) { heap[i] = heap[j]; i = j; j = i << 1; } else { break; } } heap[i] = tmp; }
inttop(int *heap) { return heap[1]; }
intlastStoneWeight(int *stones, int stonesSize) { if (stonesSize == 1) { return stones[0]; } if (stonesSize == 2) { returnfabs(stones[0] - stones[1]); } int heap[stonesSize + 2], heapSize = 0; for (int i = 0; i < stonesSize; i++) { push(heap, &heapSize, stones[i]); }
while (heapSize > 1) { int a = top(heap); pop(heap, &heapSize); int b = top(heap); pop(heap, &heapSize); if (a > b) { push(heap, &heapSize, a - b); } } return heapSize ? top(heap) : 0; }
复杂度分析
时间复杂度:O(n\log n),其中 n 是石头数量。每次从队列中取出元素需要花费 O(\log n) 的时间,最多共需要粉碎 n - 1 次石头。