본문 바로가기

Python191

[Python] 트라이 자료구조 구현(Trie) 트라이 자료구조는 검색에 최적화된 자료구조이다 자식 노드가 여러 개인 트리 형태로 구성된다고 이해하면 된다. https://leetcode.com/problems/implement-trie-prefix-tree/ Implement Trie (Prefix Tree) - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 위의 문제를 기준으로 구현했다. class TrieNode: def __init__(self): self.word = False self.childre.. 2022. 4. 30.
Python 힙 구현 힙 자료구조를 만족하려면 두 가지 조건(최소 힙 기준) 1. 부모 노드가 자식 노드보다 작다. 2. 트리의 모양이 완전 이진트리의 형태. 완전 이진트리는 마지막 레벨을 제외하고 모든 노드가 왼쪽에서 오른쪽으로 채워져 있는 트리 -> 리스트로 구현 class BinaryHeap: def __init__(self): self.items = [None] def __len__(self): return len(self.items) - 1 # 위로 올라가는거 def _percolate_up(self): index = len(self) parent = index // 2 while parent > 0: if self.items[parent] > self.items[index]: self.items[parent], s.. 2022. 4. 23.
[Python] shorten url (base64, url safe base64) URL에는 많은 정보가 담김. 그러다 보니 URL이 길어지는 문제가 발생 -> 불편하다! -> 이를 줄이기 위해 shorten url에 대한 고민이 생김 어떤 값을 Encode와 Decode를 하는 여러 가지 방법이 있는데, 알파벳과 로마자로 encode 하는 방식을 base62라고 함 1. a-z : 26개 2. A-Z : 26개 3. 0-9 : 10개 총합 : 62 그래서 base62 특수문자 2개 추가하면 base64 근데 여기 추가되는 두 개 특수문자가 + 와 /인데 이는 url에서 특별한 의미를 가지기 때문에 이렇게 쓰면 안 됨. 그래서 각각 - , _ 로 변환해준 게 base64 url-safe 아래 문제를 풀어봐도 좋겠다. https://leetcode.com/problems/encode-a.. 2022. 4. 23.
[Python] 수행시간 f string 코드 수행 시간 체크할 때 import time 해서 사용하는데, 그게 보기 불편하다. python f string 포맷팅을 사용해서 쉽게 보자 import time start = time.time() print(15 % (2 ** 15)) print(f'{time.time()-start:.3f} sec') # 실행결과 : 0.001 sec start = time.time() print(15 % (1 2022. 4. 21.
[LeetCode] Balanced Binary Tree (균형 이진 트리 확인 Python) https://leetcode.com/problems/balanced-binary-tree/ Balanced Binary Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 이진트리가 균형 잡힌 트리인지 확인하는 문제 -> 균형 잡혔단 뜻은 모든 노드의 서브 트리 간의 높이 차이가 1 이하 깔끔한 풀이 class Solution: def isBalanced(self, root): self.bal = True def dfs(node): if not node.. 2022. 4. 20.
[LeetCode] Trim a Binary Search Tree (트리 순환 재귀) https://leetcode.com/problems/trim-a-binary-search-tree/ Trim a Binary Search Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 재귀로 트리를 선회하는 방식이 이제 이해가 되는 거 같다. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.va.. 2022. 4. 15.
[LeetCode] Spiral Matrix II (나선 매트릭스 순환) https://leetcode.com/problems/spiral-matrix-ii/ Spiral Matrix II - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 나선 방향 매트릭스 순환에 대한 문제다. 아주 참신한 방법으로 풀이한 방법이 있어 남기려 한다. class Solution: def generateMatrix(self, n: int) -> List[List[int]]: matrix = [[0] * n for _ in range(n)] x, y, d.. 2022. 4. 13.
[LeetCode] Game of Life https://leetcode.com/problems/game-of-life/ Game of Life - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 주위 살아있는 세포들의 개수를 세서 살아갈지 죽을지를 결정하는 문제다. 결론은 주위에 세포가 몇 개 살아있는지를 세면 된다. class Solution: def gameOfLife(self, board: List[List[int]]) -> None: """ Do not return anything, modify .. 2022. 4. 12.
[Python] 피보나치 구현 정리 피보나치를 구현하는 방법에 대해 정리 1. 기본 재귀 def fibo(n): if n == 0: return 0 if n == 1: return 1 return fibo(n-1) + fibo(n-2) 2. bottom up 방식 def fibo(n): if n == 0: return 0 if n == 1: return 1 memo = [0] * (n + 1) memo[1] = 1 for i in range(2, n + 1): memo[i] = memo[i - 1] + memo[i - 2] return memo[n] 위 코드는 공간 복잡도가 n이 커짐에 따라 선형적으로 증가하기 때문에 O(n) 3. bottom up 방식 + 공간 복잡도 효율 def fibo(n): if n == 0: return 0 me.. 2022. 4. 10.
[LeetCode] Diameter of Binary Tree (이진트리 가장 긴 경로) https://leetcode.com/problems/diameter-of-binary-tree/ Diameter of Binary Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com class Solution: longest: int = 0 def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: def dfs(node): if not node: return -1 left = dfs(node.l.. 2022. 4. 8.
[LeetCode] Maximum Depth of Binary Tree (이진트리 최대 깊이 구하기) https://leetcode.com/problems/maximum-depth-of-binary-tree/ Maximum Depth of Binary Tree - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 트리에서 깊이(Depth)는 루트에서부터 현재 노드까지의 거리이다. 최대 깊이는 리프 노드까지 거리 중 가장 긴 거리를 구하면 된다. 재귀 방식 # Definition for a binary tree node. # class TreeNode: # def _.. 2022. 4. 8.
[Python] 순열 조합 구현 순열 def permute(self, nums: List[int]) -> List[List[int]]: answer = [] prev_elements = [] def dfs(elements): if len(elements) == 0: answer.append(prev_elements[:]) return for e in elements: next_elements = elements[:] next_elements.remove(e) prev_elements.append(e) dfs(next_elements) prev_elements.pop() dfs(nums) return answer 조합 def combine(self, n: int, k: int) -> List[List[int]]: answer = [] n.. 2022. 4. 8.
[LeetCode] Swapping Nodes in a Linked List https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ Swapping Nodes in a Linked List - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 문제 풀이 접근이 어려웠다. 왼쪽까지 움직이고 왼쪽부터 next가 null일 때까지 움직이면 right가 나오는 것을 캐치하면 풀 수 있는 문제 단순 val 바꿔주는 코드 class Solution: def swapNodes(self, head:.. 2022. 4. 4.
[LeetCode] Longest Substring Without Repeating Characters https://leetcode.com/problems/longest-substring-without-repeating-characters/ Longest Substring Without Repeating Characters - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 중복없는 가장 긴 증가하는 부분수열 문제 투 포인터와 dict 자료구조를 활용하면 된다. 예전 풀이 class Solution: def lengthOfLongestSubstring(self, .. 2022. 4. 3.
[LeetCode] Next Permutation https://leetcode.com/problems/next-permutation/ Next Permutation - LeetCode Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview. leetcode.com 다음 순열의 값을 찾아내는 문제 순열 규칙을 알게 되었다. 알듯 말듯 아리송하게 풀다가 결국 못 풀었다. 풀이 알고리즘은 1. 리스트 오른쪽부터 왼쪽으로 탐색하며 오른쪽 원소와 왼쪽 원소를 비교해서 값이 작아진 경우를 찾는다. - 만약 끝까지 찾지 못하였으면 리스트 전체가 역순으로 정렬되어 있으므로.. 2022. 4. 3.