题目
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/31/
个人解法
测试用例数(个) |
执行用时(ms) |
战胜 |
21 |
76 |
98.66% |
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
var len = matrix.length;
var loopNum = ~~(len / 2);
for (var i = 0 ; i < loopNum ; i++) {
for (var j = i ; j < len - i - 1 ; j++) {
var exchangePoints = [
[i, j],
[j, len - i - 1],
[len - i - 1, len - j - 1],
[len - j - 1, i]
];
var currentValue = matrix[exchangePoints[0][0]][exchangePoints[0][1]];
exchangePoints.forEach(function(point, index) {
var nextPoint = exchangePoints[(index + 1) % exchangePoints.length];
var tmp = matrix[nextPoint[0]][nextPoint[1]];
matrix[nextPoint[0]][nextPoint[1]] = currentValue;
currentValue = tmp;
});
}
}
return matrix;
};
最快解法
测试用例数(个) |
执行用时(ms) |
战胜 |
21 |
56 |
100% |
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
var i, j, temp;
var len = matrix.length;
for (i = 0; i < len - 1; i++) {
for (j = i; i + j < len -1; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[len - 1 - j][i];
matrix[len - 1 - j][i] = matrix[len - 1 - i][len - 1 - j];
matrix[len - 1 - i][len - 1 - j] = matrix[j][len - 1 - i];
matrix[j][len - 1 - i] = temp;
}
}
};
分析