Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 08339d1

Browse files
最后一块石头的重量 优先队列
1 parent 9e1a9e9 commit 08339d1

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* @lc app=leetcode.cn id=1046 lang=java
3+
*
4+
* [1046] 最后一块石头的重量
5+
*
6+
* https://leetcode-cn.com/problems/last-stone-weight/description/
7+
*
8+
* algorithms
9+
* Easy (61.48%)
10+
* Likes: 128
11+
* Dislikes: 0
12+
* Total Accepted: 46.2K
13+
* Total Submissions: 70.5K
14+
* Testcase Example: '[2,7,4,1,8,1]'
15+
*
16+
* 有一堆石头,每块石头的重量都是正整数。
17+
*
18+
* 每一回合,从中选出两块 最重的 石头,然后将它们一起粉碎。假设石头的重量分别为 x 和 y,且 x <= y。那么粉碎的可能结果如下:
19+
*
20+
*
21+
* 如果 x == y,那么两块石头都会被完全粉碎;
22+
* 如果 x != y,那么重量为 x 的石头将会完全粉碎,而重量为 y 的石头新重量为 y-x。
23+
*
24+
*
25+
* 最后,最多只会剩下一块石头。返回此石头的重量。如果没有石头剩下,就返回 0。
26+
*
27+
*
28+
*
29+
* 示例:
30+
*
31+
* 输入:[2,7,4,1,8,1]
32+
* 输出:1
33+
* 解释:
34+
* 先选出 7 和 8,得到 1,所以数组转换为 [2,4,1,1,1],
35+
* 再选出 2 和 4,得到 2,所以数组转换为 [2,1,1,1],
36+
* 接着是 2 和 1,得到 1,所以数组转换为 [1,1,1],
37+
* 最后选出 1 和 1,得到 0,最终数组转换为 [1],这就是最后剩下那块石头的重量。
38+
*
39+
*
40+
*
41+
* 提示:
42+
*
43+
*
44+
* 1 <= stones.length <= 30
45+
* 1 <= stones[i] <= 1000
46+
*
47+
*
48+
*/
49+
50+
// @lc code=start
51+
class Solution {
52+
public int lastStoneWeight(int[] stones) {
53+
PriorityQueue<Integer> queue = new PriorityQueue<>((x, y) -> y - x);
54+
for (int stone : stones) {
55+
queue.add(stone);
56+
}
57+
while (!queue.isEmpty()) {
58+
if (queue.size() == 1) {
59+
return queue.poll();
60+
}
61+
int y = queue.poll();
62+
int x = queue.poll();
63+
if (y == x) {
64+
continue;
65+
}
66+
queue.add(y - x);
67+
}
68+
return 0;
69+
}
70+
}
71+
// @lc code=end
72+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /