diff --git a/2giwon/MinOperations.kt b/2giwon/MinOperations.kt new file mode 100644 index 0000000..b5c70bd --- /dev/null +++ b/2giwon/MinOperations.kt @@ -0,0 +1,42 @@ +import kotlin.math.min + +class MinOperations { + fun minOperations(nums: IntArray, x: Int): Int { + var sum = 0 + var end = 0 + var start = nums.lastIndex + var result = nums.size + 1 + + while(sum < x && end < nums.size) { + sum += nums[end++] + } + + if (end == nums.size && sum != x) { + return -1 + } + + if (end == nums.size && sum == x) { + return nums.size + } + + var count = end + while (end > -1) { + if (sum > x) { + if (end == 0) break + sum -= nums[(end--) - 1] + count-- + } else if (sum < x) { + sum += nums[start--] + count++ + } else { + result = min(result, count) + if (end == 0) break + sum -= nums[(end--) - 1] + count-- + } + } + + return if (result > nums.size) -1 else result + + } +} \ No newline at end of file diff --git a/2giwon/ValidAnagram.kt b/2giwon/ValidAnagram.kt new file mode 100644 index 0000000..45761f5 --- /dev/null +++ b/2giwon/ValidAnagram.kt @@ -0,0 +1,31 @@ +class ValidAnagram { + fun isAnagram(s: String, t: String): Boolean { + + val map1 = HashMap() + val map2 = HashMap() + + s.forEach { + if (map1[it] != null) { + map1[it] = (map1[it] ?: 0) + 1 + } else { + map1[it] = 1 + } + } + + t.forEach { + if (map2[it] != null) { + map2[it] = (map2[it] ?: 0) + 1 + } else { + map2[it] = 1 + } + } + + t.forEach { + if (map1[it] == map2[it]) { + map1.remove(it) + map2.remove(it) + } + } + return map1.size == 0 && map2.size == 0 + } +} \ No newline at end of file diff --git a/BeokBeok/Binary Tree Cameras.kt b/BeokBeok/Binary Tree Cameras.kt new file mode 100644 index 0000000..f057698 --- /dev/null +++ b/BeokBeok/Binary Tree Cameras.kt @@ -0,0 +1,28 @@ +/** + * 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 { + + var res = 0 + + fun minCameraCover(root: TreeNode?): Int { + return (if (dfs(root) < 1) 1 else 0) + res + } + + fun dfs(root: TreeNode?): Int { + if (root == null) return 2 + val (left, right) = dfs(root.left) to dfs(root.right) + if (left == 0 || right == 0) { + res++ + return 1 + } + return if (left == 1 || right == 1) 2 else 0 + } +} diff --git a/BeokBeok/Binary Tree Tilt.kt b/BeokBeok/Binary Tree Tilt.kt new file mode 100644 index 0000000..9265272 --- /dev/null +++ b/BeokBeok/Binary Tree Tilt.kt @@ -0,0 +1,21 @@ +class Solution { + var result = 0 + + fun findTilt(root: TreeNode?): Int { + calculateTilt(root) + return result + } + + fun calculateTilt(root: TreeNode?): Int { + return when { + root == null -> 0 + else -> { + val left = calculateTilt(root.left) + val right = calculateTilt(root.right) + result += Math.abs(left - right) + + left + right + root.`val` + } + } + } +} diff --git a/BeokBeok/Coin Change.kt b/BeokBeok/Coin Change.kt new file mode 100644 index 0000000..74bfdb5 --- /dev/null +++ b/BeokBeok/Coin Change.kt @@ -0,0 +1,13 @@ +class Solution { + fun coinChange(coins: IntArray, amount: Int): Int { + val dp = Array(amount + 1) { amount + 1 }.apply { + set(0, 0) + } + for (i in 1..amount) { + for (j in coins.indices) { + if (coins[j] <= i) dp[i] = dp[i].coerceAtMost(dp[i - coins[j]] + 1) + } + } + return if (dp[amount] > amount) -1 else dp[amount] + } +} diff --git a/BeokBeok/Combination Sum IV.kt b/BeokBeok/Combination Sum IV.kt new file mode 100644 index 0000000..1a8903d --- /dev/null +++ b/BeokBeok/Combination Sum IV.kt @@ -0,0 +1,13 @@ +class Solution { + fun combinationSum4(nums: IntArray, target: Int): Int { + val result = Array(target + 1) { 0 }.also { + it[0] = 1 + } + for (i in 1 until result.size) { + for (j in nums.indices) { + if (i - nums[j] >= 0) result[i] += result[i - nums[j]] + } + } + return result[target] + } +} diff --git a/BeokBeok/Count Primes.kt b/BeokBeok/Count Primes.kt new file mode 100644 index 0000000..05f9a4e --- /dev/null +++ b/BeokBeok/Count Primes.kt @@ -0,0 +1,19 @@ +class Solution { + fun countPrimes(n: Int): Int { + if (n == 0 || n == 1) return 0 + + val notPrime = Array(n) { false } + var count = 0 + (2 until n) + .forEach { + if (notPrime[it]) return@forEach + count++ + var index = 2 + while (index * it < n) { + notPrime[index*it] = true + index++ + } + } + return count + } +} diff --git a/BeokBeok/Course Schedule.kt b/BeokBeok/Course Schedule.kt new file mode 100644 index 0000000..d37c5f5 --- /dev/null +++ b/BeokBeok/Course Schedule.kt @@ -0,0 +1,28 @@ +class Solution { + fun canFinish(numCourses: Int, prerequisites: Array): Boolean { + val matrix = Array(numCourses) { + Array(numCourses) { 0 } + } + val indegree = Array(numCourses) { 0 } + + repeat(prerequisites.size) { + val target = prerequisites[it][0] + val preCondition = prerequisites[it][1] + if (matrix[preCondition][target] == 0) indegree[target]++ + matrix[preCondition][target] = 1 + } + val queue: Queue = LinkedList() + repeat(indegree.size) { + if (indegree[it] == 0) queue.offer(it) + } + var count = 0 + while (queue.isNotEmpty()) { + val course = queue.poll() + count++ + repeat(numCourses) { + if (matrix[course][it] != 0 && --indegree[it] == 0) queue.offer(it) + } + } + return count == numCourses + } +} diff --git a/BeokBeok/Design HashMap.kt b/BeokBeok/Design HashMap.kt new file mode 100644 index 0000000..76f5527 --- /dev/null +++ b/BeokBeok/Design HashMap.kt @@ -0,0 +1,31 @@ +class MyHashMap() { + + /** Initialize your data structure here. */ + val map = Array(1_000_001) { -1 }.apply { + fill(-1) + } + + /** value will always be non-negative. */ + fun put(key: Int, value: Int) { + map[key] = value + } + + /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ + fun get(key: Int): Int { + return map[key] + } + + /** Removes the mapping of the specified value key if this map contains a mapping for the key */ + fun remove(key: Int) { + map[key] = -1 + } + +} + +/** + * Your MyHashMap object will be instantiated and called as such: + * var obj = MyHashMap() + * obj.put(key,value) + * var param_2 = obj.get(key) + * obj.remove(key) + */ diff --git a/BeokBeok/Find the Most Competitive Subsequence.kt b/BeokBeok/Find the Most Competitive Subsequence.kt new file mode 100644 index 0000000..9b73b55 --- /dev/null +++ b/BeokBeok/Find the Most Competitive Subsequence.kt @@ -0,0 +1,19 @@ +class Solution { + fun mostCompetitive(nums: IntArray, k: Int): IntArray { + val result = IntArray(k) + var targetIndex = 0 + for (i in nums.indices) { + while ( + targetIndex > 0 && + result[targetIndex - 1] > nums[i] && + targetIndex - i + nums.lastIndex >= k + ) { + targetIndex-- + } + if (targetIndex < k) { + result[targetIndex++] = nums[i] + } + } + return result + } +} diff --git a/BeokBeok/Find the Town Judge.kt b/BeokBeok/Find the Town Judge.kt new file mode 100644 index 0000000..cc0d26b --- /dev/null +++ b/BeokBeok/Find the Town Judge.kt @@ -0,0 +1,13 @@ +class Solution { + fun findJudge(n: Int, trust: Array): Int { + val counts = Array(n + 1) { 0 } + for (item in trust) { + counts[item[0]]-- + counts[item[1]]++ + } + for (i in 1..n) { + if (counts[i] == n - 1) return i + } + return -1 + } +} diff --git a/BeokBeok/Island Perimeter.kt b/BeokBeok/Island Perimeter.kt new file mode 100644 index 0000000..5d8b545 --- /dev/null +++ b/BeokBeok/Island Perimeter.kt @@ -0,0 +1,15 @@ +class Solution { + fun islandPerimeter(grid: Array): Int { + var (island, adjacency) = 0 to 0 + grid.forEachIndexed { rowIndex, row -> + row.forEachIndexed { colIndex, _ -> + if (row[colIndex] == 1) { + island++ + if (rowIndex + 1 < grid.size && grid[rowIndex + 1][colIndex] == 1) adjacency++ + if (colIndex + 1 < row.size && row[colIndex + 1] == 1) adjacency++ + } + } + } + return island * 4 - adjacency * 2 + } +} diff --git a/BeokBeok/Longest String Chain.kt b/BeokBeok/Longest String Chain.kt new file mode 100644 index 0000000..d9830d8 --- /dev/null +++ b/BeokBeok/Longest String Chain.kt @@ -0,0 +1,18 @@ +class Solution { + fun longestStrChain(words: Array): Int { + val dp = mutableMapOf() + var res = 0 + words + .sortedBy { it.length } + .forEach { word -> + var best = 0 + repeat(word.length) { + val prev = word.substring(0, it) + word.substring(it + 1) + best = Math.max(best, dp.getOrDefault(prev, 0) + 1) + } + dp[word] = best + res = Math.max(res, best) + } + return res + } +} diff --git a/BeokBeok/Maximum Subarray.kt b/BeokBeok/Maximum Subarray.kt new file mode 100644 index 0000000..4716872 --- /dev/null +++ b/BeokBeok/Maximum Subarray.kt @@ -0,0 +1,11 @@ +class Solution { + fun maxSubArray(nums: IntArray): Int { + var result = nums[0] + var max = nums[0] + for (i in 1 until nums.size) { + max = nums[i] + if (max > 0) max else 0 + result = result.coerceAtLeast(max) + } + return result + } +} diff --git a/BeokBeok/Merge Two Sorted Lists.kt b/BeokBeok/Merge Two Sorted Lists.kt new file mode 100644 index 0000000..7a69a92 --- /dev/null +++ b/BeokBeok/Merge Two Sorted Lists.kt @@ -0,0 +1,25 @@ +/** + * 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? { + return when { + list1 == null -> list2 + list2 == null -> list1 + list1.`val` <= list2.`val` -> { + list1.next = mergeTwoLists(list1.next, list2) + list1 + } + else -> { + list2.next = mergeTwoLists(list1, list2.next) + list2 + } + } + } +} diff --git a/BeokBeok/Middle of the Linked List.kt b/BeokBeok/Middle of the Linked List.kt new file mode 100644 index 0000000..6159aad --- /dev/null +++ b/BeokBeok/Middle of the Linked List.kt @@ -0,0 +1,12 @@ +class Solution { + fun middleNode(head: ListNode?): ListNode? { + return makeMiddle(head, head) + } + fun makeMiddle(slow: ListNode?, fast: ListNode?): ListNode? { + return when { + fast == null -> slow + fast.next == null -> slow + else -> makeMiddle(slow?.next, fast.next.next) + } + } +} diff --git a/BeokBeok/Minimum Operations to Reduce X to Zero.kt b/BeokBeok/Minimum Operations to Reduce X to Zero.kt new file mode 100644 index 0000000..217e66f --- /dev/null +++ b/BeokBeok/Minimum Operations to Reduce X to Zero.kt @@ -0,0 +1,19 @@ +class Solution { + fun minOperations(nums: IntArray, x: Int): Int { + val target = -x + nums.sum() + if (target == 0) return nums.size + + val map = mutableMapOf() + map[0] = -1 + var (sum, res) = 0 to Int.MIN_VALUE + + for (i in nums.indices) { + sum += nums[i] + if (map.containsKey(sum - target)) { + res = Math.max(res, i - map[sum - target]!!) + } + map[sum] = i + } + return if (res == Int.MIN_VALUE) -1 else nums.size - res + } +} diff --git a/BeokBeok/Minimum Remove to Make Valid Parentheses.kt b/BeokBeok/Minimum Remove to Make Valid Parentheses.kt new file mode 100644 index 0000000..fb351e0 --- /dev/null +++ b/BeokBeok/Minimum Remove to Make Valid Parentheses.kt @@ -0,0 +1,22 @@ +class Solution { + fun minRemoveToMakeValid(s: String): String { + val (open, close) = '(' to ')' + val result = s.toCharArray() + val bracketIndexes = Stack() + s.forEachIndexed { index, c -> + when (c) { + open -> bracketIndexes.push(index) + close -> { + if (bracketIndexes.isNotEmpty()) bracketIndexes.pop() + else result[index] = '-' + } + } + } + while (bracketIndexes.isNotEmpty()) { + result[bracketIndexes.pop()] = '-' + } + return result + .joinToString("") + .replace("-", "") + } +} diff --git a/BeokBeok/Pascal's Triangle II.kt b/BeokBeok/Pascal's Triangle II.kt new file mode 100644 index 0000000..fb49717 --- /dev/null +++ b/BeokBeok/Pascal's Triangle II.kt @@ -0,0 +1,26 @@ +class Solution { + fun getRow(rowIndex: Int): List { + return makeRow(mutableListOf(), 0, rowIndex) + } + + private tailrec fun makeRow(list: List, startIndex: Int, lastIndex: Int): List { + if (startIndex > lastIndex) return list + + return when (startIndex) { + 0, 1 -> makeRow(list.plus(1), startIndex + 1, lastIndex) + else -> { + val sumList = list.windowed(2, 1, false) + .map(List::sum) + makeRow( + mutableListOf().apply { + add(1) + addAll(sumList) + add(1) + }, + startIndex + 1, + lastIndex + ) + } + } + } +} diff --git a/BeokBeok/Remove All Adjacent Duplicates in String II.kt b/BeokBeok/Remove All Adjacent Duplicates in String II.kt new file mode 100644 index 0000000..2ef9035 --- /dev/null +++ b/BeokBeok/Remove All Adjacent Duplicates in String II.kt @@ -0,0 +1,11 @@ +class Solution { + fun removeDuplicates(s: String, k: Int): String { + val (counts, sb) = Array(s.length) { 0 } to StringBuilder() + s.forEach { + sb.append(it) + counts[sb.lastIndex] = 1 + if (sb.lastIndex > 0 && sb.last() == sb[sb.lastIndex - 1]) counts[sb.lastIndex - 1] else 0 + if (counts[sb.lastIndex] == k) sb.delete(sb.length - k, sb.length) + } + return sb.toString() + } +} diff --git a/BeokBeok/Rotate Image.kt b/BeokBeok/Rotate Image.kt new file mode 100644 index 0000000..4ca815c --- /dev/null +++ b/BeokBeok/Rotate Image.kt @@ -0,0 +1,12 @@ +class Solution { + fun rotate(matrix: Array): Unit { + for (col in matrix.first().indices) { + for (row in col + 1 until matrix.size) { + val temp = matrix[row][col] + matrix[row][col] = matrix[col][row] + matrix[col][row] = temp + } + } + matrix.forEach(IntArray::reverse) + } +} diff --git a/BeokBeok/Shortest Distance to a Character.kt b/BeokBeok/Shortest Distance to a Character.kt new file mode 100644 index 0000000..92aa70a --- /dev/null +++ b/BeokBeok/Shortest Distance to a Character.kt @@ -0,0 +1,16 @@ +class Solution { + fun shortestToChar(s: String, c: Char): IntArray { + val result = IntArray(s.length) + var position = -s.length + s.forEachIndexed { index, value -> + if (value == c) position = index + result[index] = index - position + } + for (i in s.lastIndex downTo 0) { + if (s[i] == c) position = i + if (position - i < 0) continue + result[i] = Math.min(result[i], position - i) + } + return result + } +} diff --git a/BeokBeok/Valid Anagram.kt b/BeokBeok/Valid Anagram.kt new file mode 100644 index 0000000..d178434 --- /dev/null +++ b/BeokBeok/Valid Anagram.kt @@ -0,0 +1,11 @@ +class Solution { + fun isAnagram(s: String, t: String): Boolean { + return s + .toCharArray() + .sorted() + .joinToString("") == t + .toCharArray() + .sorted() + .joinToString("") + } +} diff --git a/BeokBeok/Validate Stack Sequences.kt b/BeokBeok/Validate Stack Sequences.kt new file mode 100644 index 0000000..3c66572 --- /dev/null +++ b/BeokBeok/Validate Stack Sequences.kt @@ -0,0 +1,20 @@ +class Solution { + fun validateStackSequences(pushed: IntArray, popped: IntArray): Boolean { + if (pushed.size != popped.size) return false + val stack = Stack() + var (pushedIndex, poppedIndex) = 0 to 0 + while (poppedIndex < popped.size) { + if (pushedIndex < pushed.size) { + stack.push(pushed[pushedIndex]) + pushedIndex++ + } else if (pushedIndex == pushed.size) { + return false + } + while (stack.isNotEmpty() && stack.peek() == popped[poppedIndex]) { + stack.pop() + poppedIndex++ + } + } + return stack.isEmpty() + } +} diff --git a/BeokBeok/Wiggle Subsequence.kt b/BeokBeok/Wiggle Subsequence.kt new file mode 100644 index 0000000..cc5256d --- /dev/null +++ b/BeokBeok/Wiggle Subsequence.kt @@ -0,0 +1,24 @@ +class Solution { + fun wiggleMaxLength(nums: IntArray): Int { + if (nums.isEmpty()) return 0 + + val (up, down) = Array(nums.size) { 1 } to Array(nums.size) { 1 } + for (i in 1..nums.lastIndex) { + when { + nums[i] > nums[i - 1] -> { + up[i] = down[i - 1] + 1 + down[i] = down[i - 1] + } + nums[i] < nums[i - 1] -> { + down[i] = up[i - 1] + 1 + up[i] = up[i - 1] + } + else -> { + up[i] = up[i - 1] + down[i] = down[i - 1] + } + } + } + return Math.max(up[nums.lastIndex], down[nums.lastIndex]) + } +} diff --git a/improve777/AssignCookies.kt b/improve777/AssignCookies.kt new file mode 100644 index 0000000..ee5df6c --- /dev/null +++ b/improve777/AssignCookies.kt @@ -0,0 +1,20 @@ +import java.util.LinkedList + +class AssignCookies { + fun findContentsChildren(g: IntArray, s: IntArray): Int { + if (s.isEmpty()) return 0 + + val cookies = LinkedList(s.sortedDescending()) + var count = 0 + + for (children in g.sortedDescending()) { + val cookie = cookies.peek() ?: break + if (children <= cookie) { + count++ + cookies.pop() + } + } + + return count + } +} \ No newline at end of file diff --git a/improve777/BinaryTreeTilt.kt b/improve777/BinaryTreeTilt.kt new file mode 100644 index 0000000..67cc33f --- /dev/null +++ b/improve777/BinaryTreeTilt.kt @@ -0,0 +1,19 @@ +import kotlin.math.abs + +class BinaryTreeTilt { + + private var tilt = 0 + + fun findTilt(root: TreeNode?): Int { + sum(root) + return tilt + } + + private fun sum(node: TreeNode?): Int { + if (node == null) return 0 + val left = sum(node.left) + val right = sum(node.right) + tilt += abs(left - right) + return left + right + node.`val` + } +} diff --git a/improve777/FindTheTownJudge.kt b/improve777/FindTheTownJudge.kt new file mode 100644 index 0000000..feb651c --- /dev/null +++ b/improve777/FindTheTownJudge.kt @@ -0,0 +1,22 @@ +class FindTheTownJudge { + fun findJudge(n: Int, trust: Array): Int { + if (n == 1) return 1 + if (trust.isEmpty()) return -1 + + val outs = IntArray(n + 1) + val ins = IntArray(n + 1) + + trust.forEach { (src, dst) -> + outs[src]++ + ins[dst]++ + } + + for (i in 1..n) { + if (outs[i] == 0 && ins[i] == n - 1) { + return i + } + } + + return -1 + } +} diff --git a/improve777/IslandPerimeter.kt b/improve777/IslandPerimeter.kt new file mode 100644 index 0000000..e1295b8 --- /dev/null +++ b/improve777/IslandPerimeter.kt @@ -0,0 +1,50 @@ +class IslandPerimeter { + private val dx = intArrayOf(0, 0, -1, 1) + private val dy = intArrayOf(-1, 1, 0, 0) + + fun islandPerimeter(grid: Array): Int { + val tx = grid.size + val ty = grid[0].size + val visited = Array(tx) { BooleanArray(ty) } + var count = 0 + + for (i in 0 until tx) { + for (j in 0 until ty) { + count += dfs(grid, visited, i, j) + } + } + + return count + } + + private fun dfs( + grid: Array, + visited: Array, + x: Int, + y: Int + ): Int { + val tx = grid.size - 1 + val ty = grid[0].size - 1 + + if (grid[x][y] == 0) return 0 + if (visited[x][y]) return 0 + + visited[x][y] = true + + var count = 0 + + for (i in 0..3) { + val mx = x + dx[i] + val my = y + dy[i] + + if (mx !in 0..tx || my !in 0..ty) { + count += 1 + continue + } + + count += if (grid[mx][my] == 1) dfs(grid, visited, mx, my) else 1 + } + + return count + } +} diff --git a/improve777/MaximumSubarray.kt b/improve777/MaximumSubarray.kt new file mode 100644 index 0000000..72e9a33 --- /dev/null +++ b/improve777/MaximumSubarray.kt @@ -0,0 +1,14 @@ +import kotlin.math.max + +class MaximumSubarray { + fun maxSubArray(nums: IntArray): Int { + var sum = nums[0] + var sub = 0 + for (num in nums) { + sub = if (sub < 0) num else (sub + num) + sum = max(sum, sub) + } + + return sum + } +} diff --git a/improve777/MergeTwoSortedLists.kt b/improve777/MergeTwoSortedLists.kt new file mode 100644 index 0000000..ab3de04 --- /dev/null +++ b/improve777/MergeTwoSortedLists.kt @@ -0,0 +1,43 @@ +/** + * 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(l1: ListNode?, l2: ListNode?): ListNode? { + var target: ListNode? = null + + val list = mutableListOf() + + target = l1 + while (target != null) { + list.add(target.`val`) + target = target.next + } + + target = l2 + while (target != null) { + list.add(target.`val`) + target = target.next + } + + if (list.isEmpty()) return null + + list.sort() + + val result = ListNode(list.removeAt(0)) + var last = result + + for (i in list) { + val node = ListNode(i) + last.next = node + last = node + } + + return result + } +} \ No newline at end of file diff --git a/improve777/MergeTwoSortedLists2.kt b/improve777/MergeTwoSortedLists2.kt new file mode 100644 index 0000000..2cbd05b --- /dev/null +++ b/improve777/MergeTwoSortedLists2.kt @@ -0,0 +1,39 @@ +/** + * Example: + * var li = ListNode(5) + * var v = li.`val` + * Definition for singly-linked list. + * class ListNode(var `val`: Int) { + * var next: ListNode? = null + * } + */ +class MergeTwoSortedLists { + fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? { + if (list1 == null) return list2 + if (list2 == null) return list1 + + val acc = ListNode(0) + merge(acc, list1, list2) + return acc.next + } + + private tailrec fun merge(acc: ListNode?, list1: ListNode?, list2: ListNode?) { + if (list1 == null && list2 == null) return + + when { + list1 != null && list2 != null -> { + if (list1.`val` < list2.`val`) { + acc?.next = list1 + merge(acc?.next, list1.next, list2) + } else { + acc?.next = list2 + merge(acc?.next, list1, list2.next) + } + } + else -> { + acc?.next = list1 ?: list2 + merge(acc?.next, null, null) + } + } + } +} \ No newline at end of file diff --git a/improve777/MiddleOfTheLinkedList.kt b/improve777/MiddleOfTheLinkedList.kt new file mode 100644 index 0000000..9e6ee32 --- /dev/null +++ b/improve777/MiddleOfTheLinkedList.kt @@ -0,0 +1,12 @@ +class MiddleOfTheLinkedList { + fun middleNode(head: ListNode?): ListNode? { + var slow = head + var fast = head + + while (fast?.next != null) { + slow = slow?.next + fast = fast.next?.next + } + return slow + } +} diff --git a/improve777/MinimumOperationsToReduceXtoZero.kt b/improve777/MinimumOperationsToReduceXtoZero.kt new file mode 100644 index 0000000..fb9323e --- /dev/null +++ b/improve777/MinimumOperationsToReduceXtoZero.kt @@ -0,0 +1,38 @@ +import kotlin.math.max + +class MinimumOperationsToReduceXtoZero { + fun minOperations(nums: IntArray, x: Int): Int { + if (nums.isEmpty()) return -1 + val map = hashMapOf() // sum, pos + map[0] = 0 + + var sum = 0 + for (i in nums.indices) { + sum += nums[i] + map[sum] = i + } + + if (x > sum) return -1 + + val rest = sum - x + if (rest == 0) return nums.size + + var maxCount = 0 + var value = 0 + for (i in nums.indices) { + value += nums[i] + + maxCount = if (rest - value == 0) { + // + 1 하는 이유는 count 라서 + max(maxCount, i + 1) + } else { + // map 에 저장해둔 position + val diff = map[value - rest] ?: continue + max(maxCount, i - diff) + } + } + + if (maxCount == 0) return -1 + return nums.size - maxCount + } +} \ No newline at end of file diff --git a/improve777/PascalsTriangleii.kt b/improve777/PascalsTriangleii.kt new file mode 100644 index 0000000..e83798e --- /dev/null +++ b/improve777/PascalsTriangleii.kt @@ -0,0 +1,26 @@ +class PascalsTriangleii { + fun getRow(rowIndex: Int): List { + val triangle = mutableListOf(listOf(1), listOf(1, 1)) + + if (rowIndex < 2) { + return triangle[rowIndex] + } + + for (row in 2..rowIndex) { + val list = mutableListOf() + + val upperIndex = row - 1 + val upper = triangle[upperIndex] + + for (i in 0 until row + 1) { + val upperPrevNum = upper.getOrNull(i - 1) ?: 0 + val upperNum = upper.getOrNull(i) ?: 0 + val num = upperPrevNum + upperNum + list.add(num) + } + triangle.add(list) + } + + return triangle[rowIndex] + } +} diff --git a/improve777/RotateImage.kt b/improve777/RotateImage.kt new file mode 100644 index 0000000..e05dd30 --- /dev/null +++ b/improve777/RotateImage.kt @@ -0,0 +1,37 @@ +class RotateImage { + fun rotate(matrix: Array): Unit { + val n = matrix.size + + for (i in 0 until n) { + for (j in 0 until i) { + matrix[i][j] = matrix[j][i].also { matrix[j][i] = matrix[i][j] } + } + } + + for (i in 0 until n) { + matrix[i].reverse() + } + } + + fun rotate2(matrix: Array): Unit { + val n = matrix.size + + for (layer in 0 until n / 2) { + val start = layer + val end = n - 1 - layer + + for (i in start until end) { + // top + val temp = matrix[start][i] + // left -> top + matrix[start][i] = matrix[n - 1 - i][start] + // bottom -> left + matrix[n - 1 - i][start] = matrix[end][n - 1 - i] + // right -> bottom + matrix[end][n - 1 - i] = matrix[i][end] + // top -> right + matrix[i][end] = temp + } + } + } +} \ No newline at end of file