Open miracles1919 opened 2 years ago
先来道简单的,水平翻转
/**
* @param {number[][]} image
* @return {number[][]}
*/
var flipAndInvertImage = function (image) {
const n = image.length
for (let i = 0; i < n; i++) {
reverse(image[i])
}
return image
};
function reverse(arr) {
let i = 0, j = arr.length - 1
while (i < j) {
[arr[i], arr[j]] = [arr[j], arr[i]]
i++
j--
}
for(let i = 0; i < arr.length; i++) {
arr[i] ^= 1
}
}
先将矩阵沿对角线翻转,再水平翻转
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function (matrix) {
const n = matrix.length
// 对角线翻转
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
let temp = matrix[j][i]
matrix[j][i] = matrix[i][j]
matrix[i][j] = temp
}
}
// 水平翻转
for (let i = 0; i < n; i++) {
reverse(matrix[i])
}
return matrix
};
function reverse(arr) {
let i = 0, j = arr.length - 1
while (i < j) {
let temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i++
j--
}
}
按照从左到右、从上到下、从右到左、从下到上的顺序遍历数组,并用四个变量确定未遍历元素的边界
/**
* @param {number[][]} matrix
* @return {number[]}
*/
var spiralOrder = function (matrix) {
const m = matrix.length, n = matrix[0].length
let top = 0, bottom = m - 1
let left = 0, right = n - 1
const res = []
while (res.length < m * n) {
if (top <= bottom) {
// 在顶部从左往右遍历
for (let i = left; i <= right; i++) {
res.push(matrix[top][i])
}
top++
}
if (left <= right) {
// 在右侧从上往下遍历
for (let i = top; i <= bottom; i++) {
res.push(matrix[i][right])
}
right--
}
if (top <= bottom) {
// 在底部从右往左遍历
for (let i = right; i >= left; i--) {
res.push(matrix[bottom][i])
}
bottom--
}
if (left <= right) {
// 在左侧从下往上遍历
for (let i = bottom; i >= top; i--) {
res.push(matrix[i][left])
}
left++
}
}
return res
};
/**
* @param {number} n
* @return {number[][]}
*/
var generateMatrix = function (n) {
let top = 0, bottom = n - 1
let left = 0, right = n - 1
const res = new Array(n).fill(1).map(_ => [])
let num = 1
while (num <= n * n) {
if (top <= bottom) {
for (let i = left; i <= right; i++) {
res[top][i] = num++
}
top++
}
if (left <= right) {
for (let i = top; i <= bottom; i++) {
res[i][right] = num++
}
right--
}
if (top <= bottom) {
for (let i = right; i >= left; i--) {
res[bottom][i] = num++
}
bottom--
}
if (left <= right) {
for (let i = bottom; i >= top; i--) {
res[i][left] = num++
}
left++
}
}
return res
};Ï
参考:二维数组的花式遍历技巧