牛客题解 | 二维数组打印
题目
解题思路
这是一道数组遍历问题,主要思路如下:
-
问题分析:
- 给定 \(n \times n\) 的二维数组
- 需要从右上角到左下角按对角线方向打印
- 打印方向是从左上指向右下的平行线
-
解决方案:
- 分两部分打印:
- 从右上角开始,到主对角线
- 从主对角线下方开始,到左下角
- 每条对角线都是从左上到右下方向
- 分两部分打印:
-
关键点:
- 第一部分起点:\((0, n-1)\) 到 \((0, 0)\)
- 第二部分起点:\((1, 0)\) 到 \((n-1, 0)\)
- 每条对角线 \(x\) 和 \(y\) 同时增加
代码
class Printer {
public:
vector<int> arrayPrint(vector<vector<int>>& arr, int n) {
vector<int> result;
// 第一部分:从右上角到主对角线
for (int col = n-1; col >= 0; col--) {
int row = 0;
int currentCol = col;
// 沿对角线打印
while (row < n && currentCol < n) {
result.push_back(arr[row][currentCol]);
row++;
currentCol++;
}
}
// 第二部分:从主对角线下方到左下角
for (int row = 1; row < n; row++) {
int currentRow = row;
int col = 0;
// 沿对角线打印
while (currentRow < n && col < n) {
result.push_back(arr[currentRow][col]);
currentRow++;
col++;
}
}
return result;
}
};
public class Printer {
public int[] arrayPrint(int[][] arr, int n) {
int[] result = new int[n * n];
int index = 0;
// 第一部分:从右上角到主对角线
for (int col = n-1; col >= 0; col--) {
int row = 0;
int currentCol = col;
// 沿对角线打印
while (row < n && currentCol < n) {
result[index++] = arr[row][currentCol];
row++;
currentCol++;
}
}
// 第二部分:从主对角线下方到左下角
for (int row = 1; row < n; row++) {
int currentRow = row;
int col = 0;
// 沿对角线打印
while (currentRow < n && col < n) {
result[index++] = arr[currentRow][col];
currentRow++;
col++;
}
}
return result;
}
}
class Printer:
def arrayPrint(self, arr, n):
result = []
# 第一部分:从右上角到主对角线
for col in range(n-1, -1, -1):
row = 0
current_col = col
# 沿对角线打印
while row < n and current_col < n:
result.append(arr[row][current_col])
row += 1
current_col += 1
# 第二部分:从主对角线下方到左下角
for row in range(1, n):
current_row = row
col = 0
# 沿对角线打印
while current_row < n and col < n:
result.append(arr[current_row][col])
current_row += 1
col += 1
return result
算法及复杂度
- 算法:数组遍历
- 时间复杂度:\(\mathcal{O}(n^2)\) - 需要遍历整个 \(n \times n\) 数组
- 空间复杂度:\(\mathcal{O}(n^2)\) - 需要存储所有元素的结果数组

浙公网安备 33010602011771号