64. 最小路径和
class Solution {
public int minPathSum(int[][] grid) {
//典型的动态规划问题
int n = grid.length;
int m = grid[0].length;
int[][] dp = new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
//1.左上都是边界
if(i == 0 && j == 0) dp[i][j] = grid[i][j];
//2.左上都不是边界
if(i > 0 && j > 0)
dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1])+grid[i][j];
//3.左边不是边界,上边是
if(i == 0 && j > 0) dp[i][j] = dp[i][j-1]+grid[i][j];
//4.左边是边界,上边不是
if(i > 0 && j == 0) dp[i][j] = dp[i-1][j]+grid[i][j];
}
}
return dp[n-1][m-1];
}
}
48. 旋转图像
class Solution {
public void rotate(int[][] matrix) {
//思路:先对数组进行转置,再水平对称
int n = matrix.length;
int m = matrix[0].length;
//实现数组的转置
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
//实现数组以竖直为对称轴的镜像
for(int i=0;i<n;i++){//n行
for(int j=0;j<n/2;j++){//每一行转换(n/2)次
int tempp = matrix[i][j];
matrix[i][j] = matrix[i][n-j-1];
matrix[i][n-j-1] = tempp;
}
}
}
}
128. 最长连续序列
思路:
如何每次只枚举连续序列的起始数字x?
其实只需要每次在哈希表中检查是否存在 x−1即可。如果x-1存在,说明当前数x不是连续序列的起始数字,我们跳过这个数。
具体过程如下:
1、定义一个哈希表hash,将nums数组中的数都放入哈希表中。
2、遍历哈希表hash,如果当前数x的前驱x-1不存在,我们就以当前数x为起点向后枚举。
3、假设最长枚举到了数y,那么连续序列长度即为y-x+1。
4、不断枚举更新答案。
class Solution {
public int longestConsecutive(int[] nums) {
int max = 0;
int count = 0;
Set<Integer> set = new HashSet<>();
for(int num:nums){
set.add(num);
}
//注:其实自己也不知道增强for还能这样从set集合中取元素
for(int x:set){
count = 0;
if(!set.contains(x-1)){
while(set.contains(x)){
x++;
count++;
}
}
if(count > max) max = count;
}
return max;
}
}