No.1 检查某单词是否等于两单词之和
解题思路
签到题。
代码展示
class Solution {
public boolean isSumEqual(String firstWord, String secondWord, String targetWord) {
return convert(firstWord) + convert(secondWord) == convert(targetWord);
}
private long convert(String targetWord) {
long result = 0;
for (int i = 0; i < targetWord.length(); i++) {
result = result * 10 + targetWord.charAt(i) - 'a';
}
return result;
}
}
No.2 插入后的最大值
解题思路
对于负数,将 x 插入到第一个大于它的数字之前即可。
对于正数,将 x 插入到第一个小于它的数字之前即可。
如果没有,插入到末尾。
代码展示
class Solution {
public String maxValue(String n, int x) {
if (n.startsWith("-")) {
for (int i = 1; i < n.length(); i++) {
if (n.charAt(i) - '0' > x) {
return n.substring(0, i) + String.valueOf(x) + n.substring(i, n.length());
}
}
} else {
for (int i = 0; i < n.length(); i++) {
if (n.charAt(i) - '0' < x) {
return n.substring(0, i) + String.valueOf(x) + n.substring(i, n.length());
}
}
}
return n + String.valueOf(x);
}
}
No.3 使用服务器处理任务
解题思路
使用两个堆来维护当前空闲服务器和正在工作的服务器即可。
维护空闲服务器的堆按照服务器的权重排序,维护正在工作服务器的堆按照时间排序。
代码展示
class Solution {
static class Server implements Comparable
int index;
int weight;
public Server(int index, int weight) {
this.index = index;
this.weight = weight;
}
@Override
public int compareTo(Server o) {
if (weight != o.weight) {
return weight - o.weight;
}
return index - o.index;
}
}
static class Event implements Comparable
int time;
Server server;
public Event(int time, Server server) {
this.time = time;
this.server = server;
}
@Override
public int compareTo(Event o) {
if (time != o.time) {
return time - o.time;
}
return server.compareTo(o.server);
}
}
public int[] assignTasks(int[] servers, int[] tasks) {
PriorityQueue
PriorityQueue
for (int i = 0; i < servers.length; i++) {
idle.add(new Server(i, servers[i]));
}
int[] ans = new int[tasks.length];
int timeNow = 0;
for (int i = 0; i < tasks.length; i++) {
timeNow = Math.max(timeNow, i);
while (!events.isEmpty() && events.peek().time <= timeNow) {
idle.add(events.poll().server);
}
Server s;
if (idle.isEmpty()) {
Event e = events.poll();
s = e.server;
timeNow = e.time;
} else {
s = idle.poll();
}
ans[i] = s.index;
events.add(new Event(timeNow + tasks[i], s));
}
return ans;
}
}
No.4 准时抵达会议现场的最小跳过休息次数
解题思路
动态规划,`dp[i][j]` 表示走完道路 i,已经跳过休息了 j 次时的到达时间。
注意精度问题(见 `eps` 变量的使用)
代码展示
class Solution {
public int minSkips(int[] dist, int speed, int hoursBefore) {
final double inf = 1e9;
final double eps = 1e-9;
double[][] dp = new double[dist.length][dist.length];
for (int i = 0; i < dp.length; i++) {
Arrays.fill(dp[i], inf);
}
dp[0][0] = (double) dist[0] / speed;
for (int i = 1; i < dist.length; i++) {
for (int j = 0; j < i; j++) {
dp[i][j] = Math.min(dp[i][j], Math.ceil(dp[i - 1][j] - eps) + (double) dist[i] / speed);
dp[i][j + 1] = Math.min(dp[i][j + 1], dp[i - 1][j] + (double) dist[i] / speed);
}
}
for (int i = 0; i < dist.length; i++) {
if (dp[dist.length - 1][i] <= hoursBefore) {
return i;
}
}
return -1;
}
}