1046. The last stone of weight

1046. The last stone of weight

 

description:

A pile of stones, the weight of each stone are positive integers.

Each round, to choose the most important two stones, then smash them together. Suppose stone weights of x and y, and x <= y. Then crushed possible results are as follows:

If x == y, then the two will be completely crushed stone;
! If x = y, then x is a weight of the stone will be completely crushed, and the new weight of the weight of the stone y is yx.
Finally, he will only rest a stone. Returns the weight of this stone. If there is no stone left over, it returns 0.

prompt:

1 <= stones.length <= 30
1 <= stones[i] <= 1000

1 Solution:     0 MS     8.5 MB
 2  class Solution {
 . 3  public :
 . 4      int Result (The priority_queue < int > & Q) {
 . 5          int newStone = 0 ;
 . 6          the while (q.size ()> = 2 ) { // the last remaining 1 or 0 
. 7              int X = 0 , Y = 0 ;
 . 8              for ( int I = 0 ; I < 2 ; I ++) { // X must be greater than equal to Y 
. 9                  IF(I == 0 ) { // Get the two largest stone 
10                      X = q.top (), q.pop ();
 . 11                  } the else {
 12 is                      Y = q.top (), q.pop ();
 13 is                  }
 14                 // I q.top == 0 X = (), q.pop ():? Y = q.top (), q.pop (); 
15              }
 16              IF (! X = Y) { // stone weights are positive integers 
. 17                  newStone = X- Y;
 18 is                  q.push (newStone); // new stone weight in the priority queue 
19              }
 20          }
 21         IF (q.size () == . 1 ) return q.top (); // a residual 
22 is          the else  return  0 ; // no remaining the same 
23 is      }
 24      int lastStoneWeight (Vector < int > & Stones) {
 25          / * 
26          ideas:
 27              1: first data in the priority queue, descending order
 28              2: As long as the priority queue size> = 2, then remove the weight of the two largest stone
 29              3: when two stones by weight are equal, these two grinding stones, POP ()
 30              . 4: if equal, the difference between the calculated two stones (positive integer) in the priority queue
 31 is              5: until the priority queue length is 1 or 0, return results ;
 32             6: 1 length, the weight of the returned stone
 33 is              7: length of 0, returns 0
 34 is          * / 
35          The priority_queue < int > Q; // priority queue, the default descending order 
36          for ( int Data: Stones) {
 37 [              q.push (Data);
 38 is          }
 39          return Result (Q);
 40      }
 41 is };

 

Guess you like

Origin www.cnblogs.com/NirobertEinteson/p/12002818.html