Skip to content

Commit 408ab73

Browse files
committed
Add 0867 Solution.js and README.md
1 parent b0f34a7 commit 408ab73

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 转置矩阵
2+
3+
### 题目描述
4+
5+
给定一个矩阵 `A`, 返回 `A` 的转置矩阵。
6+
7+
矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
8+
9+
**示例 1**
10+
11+
```
12+
输入:[[1,2,3],[4,5,6],[7,8,9]]
13+
输出:[[1,4,7],[2,5,8],[3,6,9]]
14+
```
15+
16+
**示例 2**
17+
18+
```
19+
输入:[[1,2,3],[4,5,6]]
20+
输出:[[1,4],[2,5],[3,6]]
21+
```
22+
23+
**提示**
24+
25+
1. `1 <= A.length <= 1000`
26+
2. `1 <= A[0].length <= 1000`
27+
28+
### 解题思路
29+
30+
**思路**
31+
32+
尺寸为 `R x C` 的矩阵 `A` 转置后会得到尺寸为 `C x R` 的矩阵 `ans`,对此有 `ans[c][r] = A[r][c]`
33+
34+
让我们初始化一个新的矩阵 `ans` 来表示答案。然后,我们将酌情复制矩阵的每个条目。
35+
36+
**算法**
37+
38+
```javascript
39+
var transpose = function (A) {
40+
if ( A.length === 1 && A[0].length === 1 ) return A;
41+
let tran_matrix = [];
42+
for ( let i = 0; i < A[0].length; ++i ) {
43+
tran_matrix[i] = [];
44+
for ( let j = 0; j < A.length; ++j ) {
45+
tran_matrix[i][j] = A[j][i];
46+
}
47+
}
48+
return tran_matrix;
49+
};
50+
```
51+
52+
**复杂度分析**
53+
54+
- 时间复杂度:*O*(*R**C*),其中 *R**C* 是给定矩阵 `A` 的行数和列数。
55+
- 空间复杂度:*O*(*R**C*),也就是答案所使用的空间。
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[][]} A
3+
* @return {number[][]}
4+
*/
5+
6+
/**
7+
* Author: Mcnwork2018
8+
*/
9+
10+
var transpose = function (A) {
11+
if ( A.length === 1 && A[0].length === 1 ) return A;
12+
let tran_matrix = [];
13+
for ( let i = 0; i < A[0].length; ++i ) {
14+
tran_matrix[i] = [];
15+
for ( let j = 0; j < A.length; ++j ) {
16+
tran_matrix[i][j] = A[j][i];
17+
}
18+
}
19+
return tran_matrix;
20+
};

0 commit comments

Comments
 (0)