566. 重塑矩阵
思路
1、先看需要变换的矩阵元素是不是超过原矩阵 或者 行列没有发生变化,直接返回原矩阵
2、将原矩阵的行列顺序按照列数重排
代码
/**
* @param {number[][]} nums
* @param {number} r
* @param {number} c
* @return {number[][]}
*/
var matrixReshape = function(nums, r, c) {
const rowLen = nums.length, colLen = nums[0] && nums[0].length;
if (r * c > rowLen * colLen || (r === rowLen && c === colLen)) return nums;
nums = nums.flat();
const ret = []
let path = []
for(let i = 0; i < nums.length; i ++) {
path.push(nums[i])
if ((i+1) % c === 0) {
ret.push(path)
path = []
}
}
return ret;
};
复杂度分析
时间复杂度 #card=math&code=O%28r%2Ac%29)
空间复杂度 #card=math&code=O%28c%29)
48. 旋转图像
思路
1、先复制一个副本
2、找出旋转之后的坐标对应关系 row = len - col - 1, col = row
代码
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
const copy = matrix.map(item => item.slice())
const len = matrix.length
for(let i = 0; i < len; i ++) {
for(let j = 0; j < len; j ++) {
matrix[i][j] = copy[len - j - 1][i];
}
}
return matrix
};
复杂度分析
时间复杂度 #card=math&code=O%28N%5E2%29)
空间复杂度 #card=math&code=O%28N%5E2%29)
73. 矩阵置零
思路
1、先遍历一遍,找到有0 的行和列
2、再遍历,将有0的行和列置0
代码
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var setZeroes = function(matrix) {
const rowSet = new Set(), colSet = new Set();
const rowLen = matrix.length, colLen = matrix[0] && matrix[0].length;
for(let i = 0; i < rowLen; i ++) {
for(let j = 0; j < colLen; j ++) {
if (matrix[i][j] === 0) {
rowSet.add(i)
colSet.add(j)
}
}
}
for(let i = 0; i < rowLen; i ++) {
for(let j = 0; j < colLen; j ++) {
if (rowSet.has(i) || colSet.has(j)) {
matrix[i][j] = 0
}
}
}
return matrix
};
复杂度分析
时间复杂度 #card=math&code=O%28row%2Acol%29)
空间复杂度 #card=math&code=O%28row%20%2B%20col%29)
289. 生命游戏
思路
1、创建一个副本
2、计算当前位置的生命状态
代码
/**
* @param {number[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var gameOfLife = function(board) {
// 创建副本
const copy = board.map(item => item.slice());
const rowLen = board.length, colLen = board[0].length;
// 遍历
for(let i = 0; i < rowLen; i ++) {
for(let j = 0; j < colLen; j ++) {
board[i][j] = calcLifeState(copy, i, j);
}
}
return board;
};
// 计算当前细胞的生命状态
function calcLifeState(matrix, rowIndex, colIndex) {
let sum = 0, rowLen = matrix.length, colLen = matrix[0].length;
for(let row = Math.max(rowIndex-1, 0); row <= Math.min(rowIndex+1, rowLen-1); row ++) {
for(let col = Math.max(colIndex-1, 0); col <= Math.min(colIndex+1, colLen-1); col ++) {
if (!(row === rowIndex && col === colIndex)) {
sum+= matrix[row][col] || 0
}
}
}
// 当前细胞为活细胞
if (matrix[rowIndex][colIndex]) {
if (sum < 2 || sum > 3) return 0;
return 1
}
// 当前为死细胞
if (sum === 3) return 1;
return 0
}
复杂度分析
时间复杂度 #card=math&code=O%28row%20%2A%20col%29)
空间复杂度 #card=math&code=O%28row%20%2A%20col%29)