[Mock] Random 12

shsh·2021년 5월 25일
0

Mock

목록 보기
46/93


처음 만난 아이들


345. Reverse Vowels of a String

Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

My Answer 1: Accepted (Runtime: 56 ms - 57.32% / Memory Usage: 15.2 MB - 37.98%)

class Solution:
    def reverseVowels(self, s: str) -> str:
        vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
        
        l = 0
        r = len(s)-1
        
        answer = list(s)
        
        while l < r:
            if answer[l] not in vowels:
                l += 1
            elif answer[r] not in vowels:
                r -= 1
            
            elif answer[l] in vowels and answer[r] in vowels:
                tmp = answer[l]
                answer[l] = answer[r]
                answer[r] = tmp
                l += 1
                r -= 1
        
        return ''.join(answer)

모음에 대문자까지 포함해야된다.

leftright 를 동시에 보면서 vowels 에 있는 문자를 가리키도록 함

둘 다 vowels 면 switch


515. Find Largest Value in Each Tree Row

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

My Answer 1: Accepted (Runtime: 44 ms - 79.94% / Memory Usage: 16.3 MB - 82.66%)

# 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 largestValues(self, root: TreeNode) -> List[int]:
        queue = [root]
        cnt = 1
        m = -float('inf')
        answer = []
        
        while queue:
            if cnt == 0:
                cnt = len(queue)
                answer.append(m)
                m = -float('inf')
            r = queue.pop(0)
            
            if r:
                if r.val > m:
                    m = r.val
                if r.left:
                    queue.append(r.left)
                if r.right:
                    queue.append(r.right)
                cnt -= 1
                
        if cnt == 0:
            answer.append(m)
        
        return answer

level-order 로 보면서 cnt 로 같은 레벨의 개수를 세줌

레벨을 다 훑으면 = cnt == 0 answer 에 max 값 append

profile
Hello, World!

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN