41 缺失的第一个正数
class Solution {
public int firstMissingPositive(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int i : nums) {
map.put(i, -1);
}
int res = 1;
while (map.containsKey(res)) {
res++;
}
return res;
}
}
42 接雨水
class Solution {
public int trap(int[] height) {
int res = 0;
// 循环每一个边,往两边进行延伸,两边都能找到较大的高度,减自己的高度就代表当前节点所能有的最高高度。
for (int i = 1; i < height.length - 1; i++) {
int leftMax = 0;
int rightMax = 0;
for (int j = i; j >= 0; j--) {
leftMax = Math.max(leftMax, height[j]);
}
for (int j = i; j < height.length; j++) {
rightMax = Math.max(rightMax, height[j]);
}
res += Math.min(leftMax, rightMax) - height[i];
}
return res;
}
}
43 字符串相乘
class Solution {
public String multiply(String num1, String num2) {
int count1 = num1.length();
int count2 = num2.length();
int[] a = new int[count1];
int[] b = new int[count2];
for (int i = count1 - 1, j = 0; i >= 0; i--,j++) {
a[j] = num1.charAt(i) - '0';
}
for (int i = count2 - 1, j = 0; i >= 0; i--,j++) {
b[j] = num2.charAt(i) - '0';
}
// 模拟运算 a[i] * b[j] 加到 c[i + j]上 ,最后再将这些数去摸相加处理
int[] res = new int[count2 + count1 + 1];
for (int i = 0; i < count1; i++) {
for (int j = 0; j < count2; j++) {
res[i + j] += a[i] * b[j];
}
}
for(int i = 0, t = 0; i < count2 + count1; i++) {
t += res[i];
res[i] = t % 10;
t = t / 10;
}
int k = res.length - 1;
while (k > 0 && res[k] == 0) {
k--;
}
StringBuilder builder = new StringBuilder();
for (int i = k; i>= 0; i--) {
builder.append(res[i]);
}
return builder.toString();
}
}