第一题
leetcode1143. 最长公共子序列
leetcode1035. 不相交的线
public class 第一题16 {
public int longestCommonSubsequence(String text1, String text2) {
int n = text1.length();
int m = text2.length();
int[][] dp = new int[n + 1][m + 1];
for (int i = 1;i <= n;i++){
for (int j = 1;j <= m;j++){
if (text1.charAt(i - 1) == text2.charAt(j - 1)){
dp[i][j] = dp[i - 1][j - 1] + 1;
}else {
dp[i][j] = Math.max(dp[i - 1][j],dp[i][j - 1]);
}
}
}
return dp[n][m];
}
}
第二题
leetcode683. K 个关闭的灯泡
思路:将bulbs——》days,然后用三指针
public class 第二题16 {
public static void main(String[] args) {
int[] bulbs = {1,3,2};
int res = kEmptySlots(bulbs, 1);
System.out.println(res);
}
public static int kEmptySlots(int[] bulbs,int k){
int n = bulbs.length;
int[] days = new int[n];
for (int i = 0;i < n;i++){
days[bulbs[i] - 1] = i + 1;
}
int ans = Integer.MAX_VALUE;
for (int left = 0,mid = 1,right = k + 1;right < n;mid++){
if (days[mid] <= Math.max(bulbs[left],bulbs[right])){
if (mid == right){
ans = Math.min(ans,Math.max(bulbs[left],bulbs[right]));
}
left = mid;
right = left + k + 1;
}
}
return ans == Integer.MAX_VALUE ? -1 : ans;
}
}
第三题
leetcode1488. 避免洪水泛滥
思路:HashMap + 有序表(TreeSet)
public class 第三题16 {
public static int[] avoidFlood(int[] rains) {
int n = rains.length;
int[] ans = new int[n];
HashMap<Integer,Integer> map = new HashMap<>();
TreeSet<Integer> zero = new TreeSet<>();
for (int i = 0;i < n;i++){
if (rains[i] == 0){
zero.add(i);
ans[i] = 1;
}else {
ans[i] = -1;
if (map.containsKey(rains[i])){
Integer ceiling = zero.ceiling(map.get(rains[i]));
if (ceiling == null){
return new int[]{};
}else {
ans[ceiling] = rains[i];
zero.remove(ceiling);
map.put(rains[i],i);
}
}else {
map.put(rains[i],i);
}
}
}
return ans;
}
}