File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments