[Mock] Random 3

shsh·2021년 5월 5일
0

Mock

목록 보기
34/93

랜덤에서 마소 문제를 또 만났어요~


832. Flipping an Image

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.

  • For example, flipping [1,1,0] horizontally results in [0,1,1].

To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.

  • For example, inverting [0,1,1] results in [1,0,0].

My Answer 1: Accepted (Runtime: 48 ms - 78.01% / Memory Usage: 14.3 MB - 24.56%)

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        for i in range(len(image)):
            image[i].reverse()
        
        for i in range(len(image)):
            for j in range(len(image[i])):
                if image[i][j]:
                    image[i][j] = 0
                else:
                    image[i][j] = 1
        
        return image

i 값들의 순서를 reverse 한 후, j 값들을 0 -> 1, 1 -> 0 으로 reverse


872. Leaf-Similar Trees

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.

My Answer 1: Accepted (Runtime: 32 ms - 65.66% / Memory Usage: 14.3 MB - 68.39%)

# 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:
        leaf1 = []
        leaf2 = []
        
        def func(root, leaf):
            if root is None:
                pass
            
            if root.left is None and root.right is None:
                leaf.append(root.val)
            
            if root.left is not None:
                func(root.left, leaf)
            if root.right is not None:
                func(root.right, leaf)
        
        func(root1, leaf1)
        func(root2, leaf2)
        
        if leaf1 == leaf2:
            return True
        
        return False

preorder 순회하면서 leaf 노드들만 leaf1, leaf2 에 저장해서 둘이 비교해주기

profile
Hello, World!

0개의 댓글

Powered by GraphCDN, the GraphQL CDN