본문 바로가기

전체 글

(55)
Leetcode 532. K-diff Pairs in an Array 오랜만에 코딩 연습을 했다. 그동안 공부를 안했어서 그런지 머리가 돌덩이가 된 느낌이고... 그래서 시간이 조금 오래 걸렸지만 해냈을 때의 뿌듯함은 말로 표현할 수 없다. 오늘 문제는 nums라는 배열과 숫자 k가 주어졌을 때, nums 배열에서 k 만큼 차이가 나는 쌍의 개수를 구하는 문제이다. Python에서 코딩 연습을 할 때 자주 쓰는 collections.Counter 을 사용하였다. Counter란? 해당 배열에서 같은 문자 / 숫자가 몇 개 나왔는지 세어 dictionary 형으로 알려주는 유용한 클래스이다. 예를 들어 arr = [1, 2, 3, 4, 2] 라는 배열이 주어졌을 때, collections.Counter(arr) 을 선언해주면, 1은 1개, 2는 2개, 3은 1개, 4는 1개..
Leetcode 938. Range Sum of BST 오늘 대학교 마지막 시험 끝! 이제부터 새롭게 시작, 모두 다 힘차게 마무리했으면 좋겠다. # 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 rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: if not root: return 0 if root.val < low: return self.rangeSumBST(root.right, low, high) el..
Leetcode 26. Remove Duplicates from Sorted Array 오랜만에 리트코드! 놀고 싶은 마음만 가득한 요즘이다... 놀 수 있을때 놀자... 오늘은 정렬된 배열에서 중복된 것을 제거하는 문제이다. class Solution: def removeDuplicates(self, nums: List[int]) -> int: i = 0 for j in range(1, len(nums)): if nums[j] != nums[i]: i += 1 nums[i] = nums[j] return i+1 간단하다! 오늘 하루 한 게 이것 뿐이지만... 뭐라도 했으니 그걸로 됐다.
Leetcode 563. Binary Tree Tilt 오늘의 Leetcode! 산뜻하게 하루를 마무리...^^ # 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 findTilt(self, root: Optional[TreeNode]) -> int: self.sum = 0 def traversal(root): if not root: return 0 left = traversal(root.left) right = traversal(root.right) self.sum += abs(lef..
Leetcode 268. Missing Number 오늘은 배열에서 Missing Number 찾기! class Solution: def missingNumber(self, nums: List[int]) -> int: for i in range(len(nums) + 1): if i not in nums: return i return None 엄 청 쉽 다 따로 설명을 하지 않아도 된다. 시간이... 좀 많이 걸리긴 했지만 오늘 할 연구가 많아서 패스...
Leetcode 1137. N-th Tribonacci Number 오늘 오전의 리트코드! n-th tribonacci 수를 구하는 것이다. 간단하지만 시간 초과를 고려하여 for문을 이용하였다. 처음에 recursive하게 코드를 구현했는데 시간 초과 난다고 퇴짜 맞았기 때문이다... class Solution: def tribonacci(self, n: int) -> int: if n == 0: return 0 t0 = 0 t1 = 1 t2 = 1 tn = 0 for i in range(n-2): tn = t0 + t1 + t2 t0 = t1 t1 = t2 t2 = tn return t2 끝!
Leetcode 20. Valid Parentheses 월요일 아침을 여는 리트코드! 오늘은 쉬운 문제로 선택했다. (연구가 시급해서... 논문도 덜읽었어...) Valid parentheses이다. class Solution: def isValid(self, s: str) -> bool: parentheses = {')': '(', '}': '{', ']' : '['} stack = [] for c in s: if c in parentheses.values(): stack.append(c) if c in parentheses.keys(): if stack == []: return False elif parentheses[c] != stack.pop(): return False return stack == [] 코드는 stack을 이용하는데, 가령 {가 마지..
Leetcode 122. Best Time to Buy and Sell Stock II 오늘은 주식 최고의 이윤을 구하는 문제이다. prices = [a, b, c]라 할 때, a b, a int: profit = 0 for i in range(len(prices) - 1): if prices[i] < prices[i + 1]: profit += (prices[i + 1] - prices[i]) return profit 간단하다! 쉽게 끝이 난다. runtime과 memor..