[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가 훨씬 빨랐다 ...*

January 24, 2026 · 김태영

[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 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 } } }

January 24, 2026 · 김태영

[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 하나를 담는 객체 ...

January 22, 2026 · 김태영

[LeetCode] Grind 169 도전

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

January 21, 2026 · 김태영

[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; } } ...

August 6, 2024 · 김태영

[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; } } ...

July 16, 2024 · 김태영

[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()][]); } } ...

July 15, 2024 · 김태영

[LeetCode] Grind 75 questions (25/75) Maximum Subarray

Grind75 문제로 풀이2 1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution { public int maxSubArray(int[] nums) { int maxCurrent = nums[0]; int maxGlobal = nums[0]; for(int i = 1; i < nums.length; i++) { maxCurrent = Math.max(nums[i], maxCurrent + nums[i]); if(maxCurrent > maxGlobal) maxGlobal = maxCurrent; } return maxGlobal; } } ...

July 14, 2024 · 김태영

[LeetCode] Grind 75 questions (21/75) Diameter of Binary Tree

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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { private int diameter = 0; // 두 점을 연결하는 가장 긴 경로, 지름 public int diameterOfBinaryTree(TreeNode root) { getHeight(root); return diameter; } public int getHeight(TreeNode node) { if (node == null) return 0; int leftHeight = getHeight(node.left); int rightHeight = getHeight(node.right); // 노드를 통해 지나가는 경로의 길이 int pathThroughNode = leftHeight + rightHeight; // 현재까지의 최대 직경 갱신 diameter = Math.max(diameter, pathThroughNode); // 현재 노드의 높이 반환 return Math.max(leftHeight, rightHeight) + 1; } }

July 13, 2024 · 김태영

[LeetCode] Grind 75 questions (22/75) Middle of the Linked List

Grind75 문제로 풀이 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode middleNode(ListNode head) { ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } return slow; } }

July 13, 2024 · 김태영