[LeetCode Grind 169] Week1 - 6. Invert Binary Tree

문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 /** * Example: * var ti = TreeNode(5) * var v = ti.`val` * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Solution { fun invertTree(root: TreeNode?): TreeNode? { if(root == null) return null; invertTree(root.left) invertTree(root.right) var temp = root.left root.left = root.right root.right = temp return root } } 전위탐색 1. 현재 노드 2. 왼쪽 서브트리 3. 오른쪽 서브트리 중위탐색 1. 왼쪽 서브트리 2. 현재 노드 3. 오른쪽 서브트리 후위탐색 1. 왼쪽 서브트리 2. 오른쪽 서브트리 3. 현재 노드 TODO. 전위,중위,후위 탐색이 필요한 경우 각각 공부해놓기 이 문제는 Grind 75에서도 다뤘다: Grind 75 - Invert Binary Tree ...

2026년 1월 28일 · 김태영

[LeetCode Grind 169] Week1 - 5. Valid Palindrome

문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution { fun isPalindrome(s: String): Boolean { var start = 0 var end = s.length - 1 while(start < end) { var f = s[start] var b = s[end] when{ !f.isLetterOrDigit() -> start++ !b.isLetterOrDigit() -> end-- f.lowercaseChar() != b.lowercaseChar() -> return false else -> {start++; end--} } } return true } } 정규식으로 풀었더니 최하위 점수를 받았다 ... 정규식은 많은 비용을 감수한다 메모하기 ... kotlin의 when은 참 편리한것같다 ... 이 문제는 Grind 75에서도 다뤘다: Grind 75 - Valid Palindrome ...

2026년 1월 27일 · 김태영

[LeetCode Grind 169] Week1 - 4. Best Time to Buy and Sell Stock

문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Solution { fun maxProfit(prices: IntArray): Int { var minPrice = Int.MAX_VALUE var maxProfit = 0; for(price in prices) { if(minPrice > price) minPrice = price else { maxProfit = max(maxProfit, price - minPrice) } } return maxProfit } } 이 문제는 Grind 75에서도 다뤘다: Grind 75 - Best Time to Buy and Sell Stock

2026년 1월 25일 · 김태영

[LeetCode Grind 169] Week1 - 2. Valid Parentheses

문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { fun isValid(s: String): Boolean { var charArr = CharArray(s.length) var top = 0; for (c in s) { when(c) { '(', '[', '{' -> charArr[top++] = c ')' -> if(top == 0 || charArr[--top] != '(') return false '}' -> if(top == 0 || charArr[--top] != '{') return false ']' -> if(top == 0 || charArr[--top] != '[') return false else -> return false } } return top == 0; } } *처음에 stack으로 풀었는데 charArray가 훨씬 빨랐다 ...* 이 문제는 Grind 75에서도 다뤘다: Grind 75 - Valid Parentheses ...

2026년 1월 24일 · 김태영

[LeetCode Grind 169] Week1 - 3. Merge Two Sorted Lists

문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 /** * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class Solution { fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { if(list1 == null && list2 == null) return null else if(list1 == null) return list2 else if(list2 == null) return list1 var a = list1; var b = list2; val answer = ListNode(0) var temp: ListNode = answer while (a != null && b != null) { if(a.`val` <= b.`val`) { temp.next = a a = a.next } else { temp.next = b b = b.next } temp = temp.next!! } temp.next = a ?: b return answer.next } } 재귀형태 풀이도 기억해두자 ... 풀이2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { if (list1 == null) return list2 if (list2 == null) return list1 return if (list1.`val` <= list2.`val`) { list1.next = mergeTwoLists(list1.next, list2) list1 } else { list2.next = mergeTwoLists(list1, list2.next) list2 } } } --- > 이 문제는 Grind 75에서도 다뤘다: [Grind 75 - Merge Two Sorted Lists](https://nullnull-kim.com/logs/2024-07-01-leetcode-grind-75-questions-3/75-merge-two-sorted-lists/)

2026년 1월 24일 · 김태영

[LeetCode Grind 169] Week1 - 1. Two Sum

문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class Solution { fun twoSum(nums: IntArray, target: Int): IntArray { val map = mutableMapOf<Int, Int>() for(i in 0 until nums.size) { // for(i in nums.indices) { val cur:Int = nums[i] val sub:Int = target - cur if(map.containsKey(sub)){ return intArrayOf(map.get(sub)!!, i) } else { map.put(cur, i) } } return intArrayOf() } } *HashMap의 get의 시간복잡도가 O(1) 이라길래 코드를 까봤다...* ## get은?👇 ```kotlin /** * Returns the value to which the specified key is mapped, or {null} if this map contains no mapping for the key. * More formally, if this map contains a mapping from a key {k} to a value {v} such that {(key==null ? knull : key.squals(k))}, then this method returns {v}; otherwise it returns {null}. (There can be at most one such mapping.) * A return valsue of {null} does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key to {null}. the {containsKey} operation may be used to distinguish these two cases. */ public V get(Object key) { Node e; return (e = getNode(key)) == null ? null : e.value; } ``` 주석 google 번역 /** * 지정된 키가 매핑된 값을 반환하거나, 이 맵에 키에 대한 매핑이 포함되어 있지 않으면 **null**을 반환합니다. * 보다 공식적으로, 이 맵에 **(key==null ? knull : key.squals(k))**와 같이 키 **k**에서 값 **v**로의 매핑이 포함되어 있는 경우 이 메서드는 **v**를 반환합니다. 그렇지 않으면 **null**을 반환합니다. (이러한 매핑은 최대 하나만 있을 수 있습니다.) * 반환 값 **null**이 반드시 맵에 키에 대한 매핑이 포함되어 있지 않음을 나타내는 것은 아닙니다. 맵이 명시적으로 키를 **null**에 매핑하는 것도 가능합니다. **containsKey** 작업을 사용하여 이 두 가지 경우를 구별할 수 있습니다. */ get의 실체, getNode는?👇 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 /** * Implements Map.get and releted methos. * 매개변수: {key} - the key * 반환: the node, or null if none */ final Node<K,V> getNode(Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n, hash; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & (hash = hash(key))]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; } Node는? 1 2 3 4 5 6 7 static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; ... } 👉 Node는 key-value 하나를 담는 객체 ...

2026년 1월 22일 · 김태영

LeetCode Grind 169 — 도전 시작과 풀이 계획

2026년도는 더 힘차게 살기 위해 1분기 목표로 Grind 169문제 풀기를 시작하겠습니다! Grind 169 첫 번째 문제 풀이 보기 →

2026년 1월 21일 · 김태영

[LeetCode] Grind 75 questions (28/75) 973. K Closest Points to Origin

Grind75 문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Solution { public int[][] kClosest(int[][] points, int k) { // 최대 힙을 사용하여 거리의 내림차순으로 정렬 PriorityQueue<int[]> maxHeap = new PriorityQueue<>( (a, b) -> (b[0] * b[0] + b[1] * b[1]) - (a[0] * a[0] + a[1] * a[1]) ); // 모든 점을 힙에 추가하고, 크기가 k를 초과하면 가장 먼 점을 제거 for (int[] point : points) { maxHeap.add(point); if (maxHeap.size() > k) { maxHeap.poll(); } } // 결과 배열 생성 및 반환 int[][] result = new int[k][2]; while (k-- > 0) { result[k] = maxHeap.poll(); } return result; } } ...

2024년 8월 6일 · 김태영

[LeetCode] Grind 75 questions (27/75) 01 Matrix

Grind75 문제로 풀이2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 class Solution { public int[][] updateMatrix(int[][] mat) { int m = mat.length; int n = mat[0].length; int[][] distances = new int[m][n]; Queue<int[]> queue = new LinkedList<>(); // 모든 셀을 무한대로 초기화하고 0인 셀을 큐에 추가 for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (mat[i][j] == 0) { distances[i][j] = 0; queue.add(new int[]{i, j}); } else { distances[i][j] = Integer.MAX_VALUE; } } } // BFS를 위한 방향 배열 int[][] directions = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; // BFS 탐색 while (!queue.isEmpty()) { int[] cell = queue.poll(); int x = cell[0]; int y = cell[1]; for (int[] dir : directions) { int newX = x + dir[0]; int newY = y + dir[1]; // 유효한 범위 내에 있고, 더 짧은 거리를 발견한 경우 업데이트 if (newX >= 0 && newX < m && newY >= 0 && newY < n) { if (distances[newX][newY] > distances[x][y] + 1) { distances[newX][newY] = distances[x][y] + 1; queue.add(new int[]{newX, newY}); } } } } return distances; } } ...

2024년 7월 16일 · 김태영

[LeetCode] Grind 75 questions (26/75) Insert Interval

Grind75 문제로 풀이2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class Solution { public int[][] insert(int[][] intervals, int[] newInterval) { List<int[]> result = new ArrayList<>(); int i = 0; int n = intervals.length; // 새로운 구간의 시작 이전에 있는 구간들을 결과에 추가 while (i < n && intervals[i][1] < newInterval[0]) { result.add(intervals[i]); i++; } // 새로운 구간과 겹치는 구간들을 병합 while (i < n && intervals[i][0] <= newInterval[1]) { newInterval[0] = Math.min(newInterval[0], intervals[i][0]); newInterval[1] = Math.max(newInterval[1], intervals[i][1]); i++; } result.add(newInterval); // 새로운 구간의 끝 이후에 있는 구간들을 결과에 추가 while (i < n) { result.add(intervals[i]); i++; } return result.toArray(new int[result.size()][]); } } ...

2024년 7월 15일 · 김태영