暑期秋招算法小灶第一天
54. 螺旋矩阵 - 力扣(LeetCode)
解题思路
- 代码如下:
public List<Integer> spiralOrder(int[][] matrix) {
int top = 0, bottom = matrix.length-1;
int left = 0, right = matrix[0].length-1;
int count = 0;
List<Integer> list = new ArrayList<Integer>();
while (count < matrix.length * matrix[0].length) {
for (int i = left; i <= right; i++) {
list.add(matrix[top][i]);
count++;
}
for (int i = top+1; i <= bottom; i++) {
list.add(matrix[i][right]);
count++;
}
if (left < right && top < bottom) {
for (int i = right-1; i >= left+1; i--) {
list.add(matrix[bottom][i]);
count++;
}
for (int i = bottom; i >= top + 1; i--) {
list.add(matrix[i][left]);
count++;
}
}
left++; top++; right--; bottom--;
}
return list;
}
59. 螺旋矩阵 II - 力扣(LeetCode)
解题思路
和上一题一样,只不过这一回我们要自己填数组
- 代码如下:
public int[][] generateMatrix(int n) {
int top = 0, bottom = n-1;
int left = 0, right = n-1;
int count = 0;
int[][] result = new int[n][n];
while (count < n * n) {
for (int i = left; i <= right; i++) {
result[top][i] = count+1;
count++;
}
for (int i = top+1; i <= bottom; i++) {
result[i][right] = count+1;
count++;
}
if (left < right && top < bottom) {
for (int i = right-1; i >= left+1; i--) {
result[bottom][i] = count+1;
count++;
}
for (int i = bottom; i >= top+1; i--) {
result[i][left] = count+1;
count++;
}
}
top++; left++; bottom--; right--;
}
return result;
}
- tips
注意在填充下层时,如果是到left+1,下一步最左边往上时要从bottom开始,不能从bottom+1开始,否则会陷入死循环
48. 旋转图像 - 力扣(LeetCode)
解题思路
要求是旋转,可以看出首先是横纵坐标互换了,尝试将横纵左边互换后发现再将矩阵左右翻转即可得到最后的正确答案。这是一个观察的过程
当然这个过程中要用到一个辅助数组。
原理讲解
总结来说就是枚举+找规律
- 代码如下
public void rotate(int[][] matrix) {
int[][] origin = new int[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
origin[i][j] = matrix[i][j];
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = origin[j][i];
}
}
for (int i = 0; i < matrix.length; i++) {
int left = 0, right = matrix[0].length - 1;
while (left < right) {
int tmp = matrix[i][right];
matrix[i][right] = matrix[i][left];
matrix[i][left] = tmp;
left++; right--;
}
}
return;
}
八股文每日一题
1、GET和POST请求的区别
2、SSL/TLS
常用于对用户密码加密、解密操作
3、五层网络体系结构