题
思
每天两道吧,一道有点少。
leetcode363
看了题解,dp。
主要是有一个小技巧没想到,dp[i][j]代表从0,0开始到i,j的和,那么对于每一个区间[row1,row2,col1,col2]而言,sum = dp[row2][col2] - dp[row1][col2] - dp[row2][col1] + dp[row1][col1]
,边界情况考虑一下即可。
时间复杂度O(m^2 n^2)
leetcode299
这题就比较简单了,直接做一个数字个数的统计就行了。
代码
leetcode363
class Solution {
public int maxSumSubmatrix(int[][] matrix, int k) {
int max = Integer.MIN_VALUE;
int[][] dp = new int[matrix.length][matrix[0].length];
dp[0][0] = matrix[0][0];
for (int i = 1; i < dp.length; i++) {
dp[i][0] = dp[i - 1][0] + matrix[i][0];
}
for (int i = 1; i < dp[0].length; i++) {
dp[0][i] = dp[0][i - 1] + matrix[0][i];
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1] + matrix[i][j];
}
}
for (int row1 = 0; row1 < matrix.length; row1++) {
for (int row2 = row1; row2 < matrix.length; row2++) {
for (int col1 = 0; col1 < matrix[0].length; col1++) {
for (int col2 = col1; col2 < matrix[0].length; col2++) {
int temp = dp[row2][col2];
if (row1 > 0) {
temp -= dp[row1 - 1][col2];
}
if (col1 > 0) {
temp -= dp[row2][col1 - 1];
}
if (row1 > 0 && col1 > 0) {
temp += dp[row1 - 1][col1 - 1];
}
if (temp > max && temp <= k) {
max = temp;
}
}
}
}
}
return max;
}
}
leetcode299
class Solution {
public String getHint(String secret, String guess) {
int countA = 0, countAll = 0;
Map<Character, Integer> secretMap = new HashMap<Character, Integer>();
Map<Character, Integer> guessMap = new HashMap<Character, Integer>();
for (int i = 0; i < secret.length(); i++) {
char s = secret.charAt(i);
char g = guess.charAt(i);
if (s == g) {
countA++;
}
secretMap.put(s, secretMap.getOrDefault(s, 0) + 1);
guessMap.put(g, guessMap.getOrDefault(g, 0) + 1);
}
for (Character character : guessMap.keySet()) {
if (secretMap.containsKey(character)) {
countAll += Math.min(guessMap.get(character), secretMap.get(character));
}
}
return countA + "A" + (countAll - countA) + "B";
}
}