最大数
179:给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。
class Solution {
public String largestNumber(int[] nums) {
PriorityQueue<String> queue = new PriorityQueue<>((x,y)-> (y+x).compareTo(x+y));
for(int num:nums){
queue.offer(String.valueOf(num));
}
StringBuilder res = new StringBuilder();
while(!queue.isEmpty()){
res.append(queue.poll());
}
if(res.charAt(0)=='0'){
return "0";
}
return res.toString();
}
}
最小数
剑指offer45:输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
class Solution {
public String minNumber(int[] nums) {
PriorityQueue<String> queue = new PriorityQueue<>((x,y)->(x+y).compareTo(y+x));
for(int num:nums){
queue.offer(String.valueOf(num));
}
StringBuilder res = new StringBuilder();
while(!queue.isEmpty()){
res.append(queue.poll());
}
return res.toString();
}
}
最少过滤器
微软笔试:一共有N个工厂,每个工厂有污染物排放。每个过滤器会过滤一个工厂一半的污染物,若一个工厂安装多个过滤器会接着过滤一般的污染物。问最少需要多少个过滤器可以过滤至少一半的总污染物。
public int solution(int[] A){
int length = A.length;
int ans = 0;
double total = 0;
PriorityQueue<Double> queue = new PriorityQueue<>(Comparator.reverseOrder());
for (int i = 0; i < length; i++) {
queue.offer((double)A[i]);
total+=A[i];
}
double temp = total/2;
while(total>temp){
ans++;
double max = queue.poll();
total -=max/2;
queue.offer(max/2);
}
return ans;
}