본문 바로가기

전체 글267

[LeetCode] Symmetric Tree 파이썬 (iterative, recursion) iterative solution (32ms) class Solution: # @param root, a tree node # @return a boolean def isSymmetric(self, root): if root is None: return True stack = [] stack.append(root.left) stack.append(root.right) while stack: p, q = stack.pop(), stack.pop() if p is None and q is None: continue if p is None or q is None or p.val != q.val: return False stack.append(p.left) stack.append(q.right) stack.ap.. 2021. 3. 31.
[LeetCode] Same Tree 파이썬 (TreeNode, recursion) class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param p, a tree node # @param q, a tree node # @return a boolean def isSameTree(self, p, q): if p is None and q is None: return True if p is not None and q is not None: return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) return False 출처: github.com.. 2021. 3. 31.
[LeetCode] Merge Sorted Array 파이썬 (modify in-place) class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ nums1[m:m+n] = nums2[:] nums1.sort() 2021. 3. 31.
[LeetCode] Remove Duplicates from Sorted List 파이썬 (Linked List, shallow copy, deepcopy) 하위 95% 솔루션 😱 64ms # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: total = [] while head: total.append(head.val) head = head.next total = list(sorted(set(total))) print(total) answer = None for i in range(len(total)): if i == 0: answer = ListNo.. 2021. 3. 31.
[LeetCode] Climbing Stairs 파이썬 (DP) 28ms class Solution: def climbStairs(self, n: int) -> int: if n == 1: return 1 elif n == 2: return 2 else: dp = [0]*(n+1) dp[1] = 1 dp[2] = 2 for i in range(3, n+1): dp[i] = dp[i-1] + dp[i-2] return dp[n] swap 사용 32 ms if n == 1: return 1 a, b = 1, 2 for i in range(2, n): a, b = b, a + b return b 2021. 3. 30.
[LeetCode] Add Binary 파이썬 (int, bin) 파이썬 내장 int, bin을 사용하면 10 to 2, 2 to 10이 가능 단 bin으로 했을 경우 0b100 이런식으로 str으로 return이 되기 때문에 slicing 필요 36ms class Solution: def addBinary(self, a: str, b: str) -> str: ans = int(a,base=2)+int(b,base=2) ans = bin(ans)[2:] return ans 한줄로는 그냥 이렇게 32ms 4ms 단축 return bin(int(a,2)+int(b,2))[2:] 2021. 3. 30.
[LeetCode] Plus One 파이썬 (join, list comprehension) class Solution: def plusOne(self, digits: List[int]) -> List[int]: digits = int("".join([str(x) for x in digits]))+1 digits = list(str(digits)) return digits 2021. 3. 30.
[LeetCode] Length of Last Word 파이썬 (rstrip, split) class Solution: def lengthOfLastWord(self, s): return len(s.rstrip(' ').split(' ')[-1]) 문제에 잘 설명이 안되어 있어서 그런지 downvote가 3천개 s = "a "이 경우에서 wrong answer가 발생하는 거에서 막혔는데 내가 생각했을때는 0이 맞다고 보는데 1로 return 해야된다고 하니 문제에서 last word라고 한것은 제일 오른쪽 끝에 공백이 있으면 그 바로 전 word의 length를 return 하는 것으로 요구한듯. 아무튼 여기서 가져갈 것은 strip을 사용하는 것. 2021. 3. 30.
[LeetCode] Maximum Subarray 파이썬 (dp, local max, global max) dp 사용 class Solution: def maxSubArray(self, nums: List[int]) -> int: dp = [num for num in nums] for i in range(1, len(nums)): dp[i] = max(dp[i-1]+nums[i], nums[i]) return max(dp) dp 미사용 class Solution: def maxSubArray(self, nums: List[int]) -> int: # 3/26/2021 microsoft prep max_sub = 0 global_max = float('-inf') for n in nums: max_sub = max(max_sub + n, n) global_max = max(max_sub, global_max) .. 2021. 3. 30.