본문 바로가기

Leetcode98

[LeetCode] Add Digits 파이썬 class Solution: def addDigits(self, num: int) -> int: if num = 2: num = list(str(num)) # print(num) num=sum([int(x) for x in num]) # print(num) len_num = len(list(str(num))) return num ['3', '8'] 11 ['1', '1'] 2 아무래도 list로 만들고 다시 sum으로 list comprehension을 수행하는게 비효율적인 과정이라서 속도가 느린편으로 나왔다. 다른 풀이 class Solution: def addDigits(self, num: int) ->.. 2021. 4. 11.
[LeetCode] Binary Tree Paths 파이썬 (Binary Tree, LCA, DFS) class Solution(object): # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): result, path = [], [] self.binaryTreePathsRecu(root, path, result) return result def binaryTreePathsRecu(self, node, path, result): if node is None: return if node.left is node.right is None: ans = "" for n in path: ans += str(n.val) + "->" result.append(ans + str(node.val)) if node.left: path... 2021. 4. 7.
[LeetCode] Valid Anagram 파이썬 (dict) class Solution: def isAnagram(self, s: str, t: str) -> bool: def get_dict(word): res = {} for c in word: if c in res: res[c] += 1 else: res[c] = 1 return sorted(res.items()) sd = get_dict(s) td = get_dict(t) return sd == td dict를 sort 하려면 sorted 안에 dict.items()를 넣어주면 된다. 아래 처럼 key를 사용해서 key, value 순으로 sort가능하다. ygseo.tistory.com/215 2021. 4. 7.
[LeetCode] Delete Node in a Linked List 파이썬 (linked list) class Solution: def deleteNode(self, node): if node and node.next: node.val = node.next.val # swap current val to next val node.next = node.next.next # jump next to next.next 2021. 4. 7.
[LeetCode] Lowest Common Ancestor 파이썬 (tree) class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): s, b = sorted([p.val, q.val]) while not s 2021. 4. 7.
[LeetCode] Palindrome Linked List 파이썬 class Solution: # @param {ListNode} head # @return {boolean} def isPalindrome(self, head): # get mid point cur = head N = 0 while cur: N += 1 cur = cur.next mid = N//2 i = 0 def reverse(head): ans = None while head: nx = head.next head.next = ans ans = head head = nx return ans first = second = head # to mid point while i < mid: second = second.next i += 1 second = reverse(second) # check palind.. 2021. 4. 6.
[LeetCode] Summary Ranges 파이썬 class Solution: # @param {integer[]} nums # @return {string[]} def summaryRanges(self, nums): if not nums: return [] start = nums[0] end = nums[0] ans = [] def beautify(a, b): if a == b: return str(a) else: return str(a) + "->" + str(b) for i in range(1,len(nums)): if (nums[i] - nums[i-1]) != 1: ans.append(beautify(start,nums[i-1])) start = nums[i] ans.append(beautify(start, nums[-1])) return an.. 2021. 4. 6.
[LeetCode] Invert Binary Tree 파이썬(recursion) recursively # 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 invertTree(self, root: TreeNode) -> TreeNode: def recu(node): if node == None: return recu(node.left) recu(node.right) node.left, node.right = node.right, node.left recu(root) return root iteratively cl.. 2021. 4. 5.
[LeetCode] Contains Duplicate II 파이썬 (dict) class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: seen = {} for idx, value in enumerate(nums): if value not in seen: seen[value] = [idx] else: seen[value] += [abs(idx - seen[value][-1])] for key in seen.keys(): if len(seen[key])>1: if sum( [x 0: return True return False seen 이라는 dict를 만들어서 value 들은 list 형식으로 추가해서 duplicate일 경우(seen에 있는 key일 경우) 현재 위치 - 기존의 가장 최근.. 2021. 4. 5.