오늘은 술 덕분에 제가 이것도 해보게 됐네요
Given an n x n binary matrix image, flip the image horizontally, then invert it, and return the resulting image.
To flip an image horizontally means that each row of the image is reversed.
To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
# flipping
for i in range(len(image)):
for j in range(len(image)//2):
temp = image[i][j]
image[i][j] = image[i][len(image)-j-1]
image[i][len(image)-j-1] = temp
# inverting
for i in range(len(image)):
for j in range(len(image)):
if image[i][j] == 0:
image[i][j] = 1
else:
image[i][j] = 0
return image
flipping
: 거꾸로 뒤집기 -> inverting
: 0 은 1 로 바꾸고 1 은 0 으로 바꾸기
순서대로 진행해주면 끝~
따로 구분할 필요 없이 flipping
과 inverting
을 한번에 해줘도 됨
class Solution:
def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
return [[1 ^ i for i in reversed(row)] for row in image]
풀이가 느려서 루션이 찾아봤는데 one-line Flex 와 함께... 내거보다 빠르다!!
reversed
함수와 XOR 사용
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
def preOrder(root, leaf):
if root is None:
pass
elif not root.left and not root.right:
leaf.append(root.val)
else:
preOrder(root.left, leaf)
preOrder(root.right, leaf)
leaf1 = []
preOrder(root1, leaf1)
leaf2 = []
preOrder(root2, leaf2)
if leaf1 == leaf2:
return True
return False
첨엔 sequence 고려를 안해서 걍 level order 로 leaf 들만 저장한 후 비교 => X
pre order 를 써야되겠다고 생각
root1
의 leaf 들과 root2
의 leaf 들을 구해서 비교 후 T/F return~
루션이들도 비슷한듯용용