触宝周赛Week 243
不会做最后一题哈哈哈
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
int ans = decode(firstWord) + decode(secondWord);
return ans == decode(targetWord);
}
private int decode(String str) {
int n = str.length();
int cnt = 0;
//从个位开始计算
for (int i = n - 1, j = 1; i >= 0; i--, j = j * 10) {
cnt += ((str.charAt(i) - 'a') * j);
}
return cnt;
}
第二题 5773. 插入后的最大值
public String maxVal(String n, int x) {
StringBuilder sb = new StringBuilder();
if (n.charAt(0) == '-') {//若为负数,idx向后移一位
for (int i = 1; i < n.length(); i++) {
if (n.charAt(i) - '0' > x) {//负数,大数往后
sb.append(n.substring(0, i)).append(x).append(n.substring(i));
return sb.toString();
}
}
} else {
for (int i = 0; i < n.length(); i++) {//正数,大数往前
if (n.charAt(i) - '0' < x) {
sb.append(n.substring(0, i)).append(x).append(n.substring(i));
return sb.toString();
}
}
}
return n + x;
}
public int[] assignTasks(int[] servers, int[] tasks) {
int n = servers.length , m = tasks.length;
int[] ans = new int[m];
//双堆解决
//权重从小到大,index从小到大
PriorityQueue<ServerState> free = new PriorityQueue<>((a , b) -> {
return a.weight == b.weight ? a.idx - b.idx : a.weight - b.weight;
});
for (int i = 0; i < n; i++) {
free.offer(new ServerState(i , servers[i] , 0));
}
PriorityQueue<ServerState> busy = new PriorityQueue<>((a , b) -> {
return a.ending == b.ending ? (a.weight == b.weight ? a.idx - b.idx : a.weight - b.weight) : a.ending - b.ending;
});
for (int i = 0; i < m; i++) {
////检测busy中是否有完成时间小于<=当前时间的服务器,若有,则从busy中取出该服务器并加入free中
while (!busy.isEmpty() && busy.peek().ending <= i){
free.offer(busy.poll());
}
// 如果暂时没有可用的服务器,就用最先完成服务的那个,也就是busy的堆顶
// 更新服务结束时间,与下标j无关,因为已经不是从j时刻开始了
if (free.isEmpty()){
ServerState top = busy.poll();
top.ending += tasks[i];
ans[i] = top.idx;
busy.offer(top);
}else {
ServerState cur = free.poll();
cur.ending = i + tasks[i];
ans[i] = cur.idx;
busy.offer(cur);
}
}
return ans;
}
class ServerState{//存储服务器的info
int idx;
int weight;
int ending;
public ServerState(int idx , int weight , int ending){
this.idx = idx;
this.weight = weight;
this.ending = ending;
}
}