본문 바로가기

컴퓨터/코테

릿코드155 - min Stack [스택] class MinStack: def __init__(self): self.stack = [] self.minStack = [] self.min = 2**31 def push(self, val: int) -> None: self.stack.append(val) self.min = self.min if val > self.min else val self.minStack.append(self.min) def pop(self) -> None: num = self.minStack.pop() self.stack.pop() if not self.minStack : self.min = 2**31 if num == self.min : self.min = min(self.minStack) def top(self) -> i.. 더보기
릿코드 2 - 두 수 더하기 (리스트) class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(); ListNode cursor = head; int up = 0; int num1, num2; while(l1 != null || l2 != null) { if(l1 == null) num1 = 0; else { num1 = l1.val; l1 = l1.next; } if(l2 == null) num2 = 0; else { num2 = l2.val; l2 = l2.next; } int tmp = num1 + num2 + up; up = tmp / 10; cursor.val = tmp % 10; if(l1 == null.. 더보기
릿코드 20 - 괄호 짝 맞추기 class Solution(object): def isValid(self, s): bracket = { '(' : 1, ')' : -1, '{' : 2, '}' : -2, '[' : 3, ']' : -3} mystack = [] for i in s : if bracket[i] > 0 : mystack.append(bracket[i]) else : if not mystack : return False if int(mystack[-1]) + bracket[i] == 0 : mystack.pop() else : return False return len(mystack) == 0 class Solution(object): def isValid(self, s): openBracket = { '[' : ']', '.. 더보기
릿코드 104 - 트리의 가장 깊은 층 # 재귀 버전 class Solution(object): def pre(self, node, count, depth): count += 1 if node.right: self.pre(node.right, count, depth) if node.left: self.pre(node.left, count, depth) if count > depth[0]: depth[0] = count def maxDepth(self, root): depth = [0] if root: self.pre(root, 0, depth) return depth[0] # iter 버전 class Solution(object): def maxDepth(self, root): stack = [(1, root)] maxDepth = 0 whi.. 더보기
백준 1068 - 트리 문제 node = int(input()) parent = [int(x) for x in input().split(' ')] deleted = int(input()) class Node : def __init__(self, data): self.data = data self.child = [] class Tree : def __init__(self, node): self.root = node self.leaf = 0 def preorder(self, node): for i in node.child : if i.data == deleted: continue self.preorder(i) if not node.child or (len(node.child) == 1 and node.child[0].data == de.. 더보기