import java.util.*;
public class BoxesDiv2{
public BoxesDiv2(){}
public int findSize(int[] candyCounts)
{
Arrays.sort(candyCounts);
for(int i=0;i<candyCounts.length;i++){
int v = candyCounts[i];
int j=1;
while(j<v){
j<<=1;
}
candyCounts[i]=j;
}
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(candyCounts.length);
for(int i=0;i<candyCounts.length;i++){
pq.add(candyCounts[i]);
}
while(!pq.isEmpty()){
Integer v1 = pq.peek();
pq.poll();
if(pq.isEmpty()){
return v1;
}
Integer v2= pq.peek();
pq.poll();
int v3 = v1+v2;
int j=1;
while(j<v3){
j<<=1;
}
pq.add(j);
}
return 1;
}
}
思路:
向上2的指数幂取整,
即1--》1;2--》2;3,4--》4;5,6,7,8--》8
(1)对所有元素向上按2的指数幂取整。
(2)使用堆,将所有元素入堆
(3)如果堆中只有一个元素,出堆,并返回改堆顶元素
(4)否则,取堆顶2个元素,并相加后,向上2的指数幂取整,入堆。
这一步,实际上只要对这2个数中大的元素乘以2即可。