728x90

LeetCode-48

Rotate Image : 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.

Answer

        :::python

class Solution: def rotate(self, matrix: List[List[int]]) -> None: if len(matrix[0])==1: return None max_length = len(matrix[0]) matrix = collections.deque(matrix) for i in range(max_length): for j in range(max_length): matrix[j].append(matrix[max_length-i-1].pop(0))

Result : 43ms Memory: 16.3mb

๋ฌธ์ œ

์ฃผ์–ด์ง„ 2D ๋ฐฐ์—ด์„ 90๋„ ํšŒ์ „์‹œํ‚ค๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

์˜ˆ์‹œ

์˜ˆ์‹œ ์ž…๋ ฅ ๋ฐฐ์—ด:

[
  [1,2,3],
  [4,5,6],
  [7,8,9]
]

์˜ˆ์‹œ ์ถœ๋ ฅ ๋ฐฐ์—ด:

[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

์ ‘๊ทผ ๋ฐฉ๋ฒ•

์ด ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” ์ด์ฐจ์› ๋ฐฐ์—ด์—์„œ ํ–‰๊ณผ ์—ด์˜ ์œ„์น˜๋ฅผ ๋ฐ”๊พธ๋Š” ๊ฒƒ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค. ์ด๋ฅผ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ์Šต๋‹ˆ๋‹ค.

ํ–‰๊ณผ ์—ด ๋ฐ”๊พธ๊ธฐ

์šฐ์„  ํ–‰๊ณผ ์—ด์˜ ์œ„์น˜๋ฅผ ๋ฐ”๊ฟ”๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. ์˜ˆ์‹œ ๋ฐฐ์—ด์„ ๋ฐ”๊พธ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ชจ์–‘์„ ๊ฐ€์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

[
  [1,4,7],
  [2,5,8],
  [3,6,9]
]

์ด์ œ ๊ฐ ํ–‰์„ ๋’ค์ง‘์œผ๋ฉด ํšŒ์ „๋œ ๋ฐฐ์—ด์ด ์™„์„ฑ๋ฉ๋‹ˆ๋‹ค.

๋Œ€๊ฐ์„  ๊ธฐ์ค€ ๋ฐ”๊พธ๊ธฐ

๋Œ€๊ฐ์„ ์— ๋Œ€ํ•ด ๋Œ€์นญ์„ ๋งŒ๋“ค์–ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.
์˜ˆ์‹œ ๋ฐฐ์—ด์„ ๋Œ€๊ฐ์„ ์œผ๋กœ ๋’ค์ง‘์œผ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ชจ์–‘์„ ๊ฐ€์ง€๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

[
  [1,4,7],
  [2,5,8],
  [3,6,9]
]

์ด์ œ ๊ฐ ํ˜•ํƒœ๋Š” ๋‘˜ ๋‹ค ๊ฐ™์€ ๋ชจ์–‘์ž…๋‹ˆ๋‹ค. ์ด ์ค‘์—์„œ ๊ฐ ํ–‰์„ ๋’ค์ง‘์–ด์ฃผ๋ฉด ํšŒ์ „๋œ ๋ฐฐ์—ด์ด ์™„์„ฑ๋ฉ๋‹ˆ๋‹ค.

์‹œ๊ฐ„ ๋ณต์žก๋„

์ด ๋ฌธ์ œ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(n^2)์ž…๋‹ˆ๋‹ค. ์ด๋Š” ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ํ•œ ๋ฒˆ์”ฉ๋งŒ ๋ฐฉ๋ฌธํ•ด์„œ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๋˜๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

๋ฐ˜์‘ํ˜•

'๐Ÿข One step' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[leetcode-706] Design HashMap  (0) 2023.05.09
[leetcode-38] Count and Say  (0) 2023.05.05
[leetcode-347] Top K Frequent Elements  (0) 2023.04.27
[leetcode-43] Multiply Strings  (0) 2023.04.26
[leetcode-14] Longest Common Prefix  (0) 2023.04.24
๋‹คํ–ˆ๋‹ค