Skip to content

Commit 90e03ff

Browse files
authored
Merge pull request chipbk10#113 from chipbk10/Heap
Solve Problem 1046 - Last Stone Weight
2 parents 71d37b0 + 8a54b48 commit 90e03ff

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package heap;
2+
3+
import java.util.PriorityQueue;
4+
5+
public class Problem1046_LastStoneWeight {
6+
7+
public int lastStoneWeight(int[] A) {
8+
int B[] = new int[1001], i = 1000;
9+
for (int a : A) B[a]++;
10+
11+
int j = 0;
12+
while (i >= 0) {
13+
14+
while (i >= 0 && B[i] == 0) i--;
15+
if (i >= 0 && B[i] != 0) {
16+
System.out.println(i);
17+
j = i;
18+
B[i]--;
19+
}
20+
21+
while (i >= 0 && B[i] != 0) i--;
22+
if (i >= 0 && B[i] != 0) {
23+
System.out.println(i);
24+
j -= i;
25+
B[i]--;
26+
B[j]++;
27+
i = Math.max(i, j);
28+
}
29+
}
30+
31+
return j;
32+
}
33+
34+
public int lastStoneWeight_usingHeap(int[] A) {
35+
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> b-a);
36+
for (int a : A) pq.offer(a);
37+
while (!pq.isEmpty()) {
38+
int a = pq.poll();
39+
if (pq.isEmpty()) return a;
40+
int b = pq.poll();
41+
if (a > b) pq.offer(a-b);
42+
}
43+
return 0;
44+
}
45+
46+
}

0 commit comments

Comments
 (0)