Problem
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
class Solution { public void rotate(int[][] matrix) { int n = matrix.length; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n/2; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[i][n-1-j]; matrix[i][n-1-j] = temp; } } } }4-way swap
class Solution { public void rotate(int[][] matrix) { int n = matrix.length; for (int i = 0; i < n/2; i++) { for (int j = i; j < n-i-1; j++) { swap(matrix, n, i, j); } } } private void swap(int[][] matrix, int n, int i, int j) { int temp = matrix[i][j]; matrix[i][j] = matrix[n-1-j][i]; matrix[n-1-j][i] = matrix[n-1-i][n-1-j]; matrix[n-1-i][n-1-j] = matrix[j][n-1-i]; matrix[j][n-1-i] = temp; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/72651.html
LeetCode[48] Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Follow up:Could you do this in-place? 復(fù)雜度O(N^2),O(1) 代碼 public void ro...
摘要:題目詳情這道題目要求我們對一個正方形矩陣進(jìn)行順時針度的翻轉(zhuǎn)。并且要求不聲明額外的空間,不能新建二維數(shù)組。輸入數(shù)組旋轉(zhuǎn)后的輸入數(shù)組想法這道題因為要求在位。所以我們需要找到一種解法,使得每次操作都是交換兩個元素的位置,最后實現(xiàn)整個矩陣的旋轉(zhuǎn)。 題目詳情 You are given an n x n 2D matrix representing an image.Rotate the ima...
摘要:每一次的旋轉(zhuǎn),其實都是正方形上的四個元素之間的相互替換。所以本質(zhì)上我們只需遍歷每種長度正方形上的一條邊,就可以完成這個正方形的旋轉(zhuǎn)。最后實現(xiàn)整個數(shù)組矩陣的旋轉(zhuǎn)代表正方形的起始位置,即,,即,代表當(dāng)前正方形上的一條邊上的一個點。 題目要求 You are given an n x n 2D matrix representing an image. Rotate the image b...
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖恪K栽谶@里做個索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當(dāng)時也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖恪K栽谶@里做個索引嘻嘻。 順序整理 1~50 1...
摘要:交換法復(fù)雜度時間空間思路為了實現(xiàn)這題,我們要用交換的方法,順序是左上先和左下交換,然后左上和右下交換,然后左上和右上交換。和類似,我們通過圈數(shù)來控制內(nèi)外的順序。代碼計算圈數(shù)左上和左下交換左上和右下交換左上和右上交換 Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image...
閱讀 1229·2021-11-24 09:39
閱讀 380·2019-08-30 14:12
閱讀 2592·2019-08-30 13:10
閱讀 2434·2019-08-30 12:44
閱讀 958·2019-08-29 16:31
閱讀 845·2019-08-29 13:10
閱讀 2434·2019-08-27 10:57
閱讀 3152·2019-08-26 13:57