diff --git a/2giwon/BeautifulArrangement.kt b/2giwon/BeautifulArrangement.kt new file mode 100644 index 0000000..c566dff --- /dev/null +++ b/2giwon/BeautifulArrangement.kt @@ -0,0 +1,26 @@ +import java.util.* + +class BeautifulArrangement { + fun countArrangement(n: Int): Int { + val arrangement = mutableListOf() + for (i in 0 until n) { + arrangement.add(i + 1) + } + + return req(n, arrangement) + } + + private fun req(n: Int, arrangement: MutableList): Int { + if (n <= 0) return 1 + var result = 0 + for (i in 0 until n) { + if (n % arrangement[i] == 0 || arrangement[i] % n == 0) { + Collections.swap(arrangement, i, n - 1) + result += req(n - 1, arrangement) + Collections.swap(arrangement, i, n - 1) + } + } + return result + } + +} \ No newline at end of file diff --git a/2giwon/ChocolatesByNumbers.kt b/2giwon/ChocolatesByNumbers.kt new file mode 100644 index 0000000..0d8d0c2 --- /dev/null +++ b/2giwon/ChocolatesByNumbers.kt @@ -0,0 +1,10 @@ +class ChocolatesByNumbers { + fun solution(N: Int, M: Int): Int { + tailrec fun solution(a: Int, b: Int): Int { + if (b == 0) return N / a + return solution(b, a % b) + } + + return solution(N, M) + } +} \ No newline at end of file diff --git a/2giwon/CombinationSum.kt b/2giwon/CombinationSum.kt new file mode 100644 index 0000000..42cdea9 --- /dev/null +++ b/2giwon/CombinationSum.kt @@ -0,0 +1,35 @@ +import java.util.* + +class CombinationSum { + private var target = 0 + fun combinationSum(candidates: IntArray, target: Int): List> { + this.target = target + return reqCal(candidates, 0, 0, Stack(), mutableListOf()) + } + + private fun reqCal(candidates: IntArray, i: Int, acc: Int, stack: Stack, answer: MutableList>): List> { + var index = i + while (index <= candidates.lastIndex) { + if (acc == target) { + answer.add(stack.toList()) + break + } + + if (acc > target) { + break + } + + if (index > candidates.lastIndex) { + break + } + + val candidate: Int = candidates[index] + stack.push(candidate) + reqCal(candidates, index, acc + candidate, stack, answer) + index++ + } + + if (!stack.empty()) stack.pop() + return answer + } +} \ No newline at end of file diff --git a/2giwon/DecodeString.kt b/2giwon/DecodeString.kt new file mode 100644 index 0000000..f056cff --- /dev/null +++ b/2giwon/DecodeString.kt @@ -0,0 +1,41 @@ +package leetcode.study + +import java.util.* + +class DecodeString { + fun decodeString(s: String): String { + var result = "" + var count = "" + val stack = Stack() + val indexStack = Stack() + + var i = 0 + while (i < s.length) { + when { + s[i] == '[' -> { + stack.push(count.toInt()) + indexStack.push(i) + count = "" + } + s[i] == ']' -> { + if (stack[stack.lastIndex] <= 1) { + stack.pop() + indexStack.pop() + } else { + stack[stack.lastIndex]-- + i = indexStack.peek() + } + } + Character.isDigit(s[i]) -> { + count += s[i] + } + else -> { + result += s[i] + } + } + i++ + } + + return result + } +} \ No newline at end of file diff --git a/2giwon/DeleteNodeBST.kt b/2giwon/DeleteNodeBST.kt new file mode 100644 index 0000000..173564d --- /dev/null +++ b/2giwon/DeleteNodeBST.kt @@ -0,0 +1,21 @@ +class DeleteNodeBST { + + fun deleteNode(root: TreeNode?, key: Int): TreeNode? { + if (root == null) return null + if (key == 0) return root + if (root.`val` == key) return merge(root.right, root.left) + + if (key < root.`val`) root.left = deleteNode(root.left, key) + if (key > root.`val`) root.right = deleteNode(root.right, key) + return root + } + + private fun merge(root: TreeNode?, node: TreeNode?): TreeNode? { + if (root == null) return node + else if (node == null) return root + + if (node.`val` < root.`val`) root.left = merge(root.left, node) + if (node.`val` > root.`val`) root.right = merge(root.right, node) + return root + } +} \ No newline at end of file diff --git a/2giwon/FindSmallestDivisorThreshold.kt b/2giwon/FindSmallestDivisorThreshold.kt new file mode 100644 index 0000000..e31ce49 --- /dev/null +++ b/2giwon/FindSmallestDivisorThreshold.kt @@ -0,0 +1,27 @@ +import kotlin.math.ceil + +class FindSmallestDivisorThreshold { + fun smallestDivisor(nums: IntArray, threshold: Int): Int { + var left = 1 + var right = 1000001 + + while (left <= right) { + val mid = left + (right - left) / 2 + val sum = sum(nums, mid) + if (sum > threshold) + left = mid + 1 + else + right = mid - 1 + } + + return left + } + + private fun sum(nums: IntArray, d: Int): Int { + var sum = 0 + for (num in nums) { + sum += ceil(num.toDouble() / d).toInt() + } + return sum + } +} \ No newline at end of file diff --git a/2giwon/IncreasingBST.kt b/2giwon/IncreasingBST.kt new file mode 100644 index 0000000..e7b3f6d --- /dev/null +++ b/2giwon/IncreasingBST.kt @@ -0,0 +1,18 @@ +class IncreasingBST { + private var current: TreeNode? = null + fun increasingBST(root: TreeNode?): TreeNode? { + val answer = TreeNode(0) + current = answer + inOrder(root) + return answer.right + } + + private fun inOrder(node: TreeNode?) { + if (node == null) return + inOrder(node.left) + node.left = null + current?.right = node + current = node + inOrder(node.right) + } +} \ No newline at end of file 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/Permutations.kt b/2giwon/Permutations.kt new file mode 100644 index 0000000..fcb4e6b --- /dev/null +++ b/2giwon/Permutations.kt @@ -0,0 +1,41 @@ +class Permutations { + private var max: Int = 0 + fun permuteUnique(nums: IntArray): List> { + val result: MutableList> = mutableListOf() + val mutableNums = nums.toMutableList() + max = nums.size + + if (nums.size <= 1) result.add(mutableNums) + else req(mutableNums, mutableListOf(), mutableSetOf(), 0, result) + + return result + } + + private fun req( + nums: MutableList, + values: MutableList, + visited: MutableSet, + depth: Int, + result: MutableList> + ) { + if (nums.size <= 1) { + values.add(nums[0]) + return + } + + for (i: Int in nums.indices) { + if (depth == 0 && visited.contains(nums[i])) continue + val v = values.toMutableList() + val nums2 = nums.toMutableList() + + v.add(nums2[i]) + if (depth == 0) visited.add(nums2[i]) + nums2.remove(nums2[i]) + req(nums2, v, visited, depth + 1, result) + + if (v.size == max) result.add(v) + } + } + + +} \ No newline at end of file diff --git a/2giwon/RangeSumBST.kt b/2giwon/RangeSumBST.kt new file mode 100644 index 0000000..26e022f --- /dev/null +++ b/2giwon/RangeSumBST.kt @@ -0,0 +1,14 @@ +class RangeSumBST { + fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int { + var result = 0 + root?.let { + if (root.`val` in low..high) { + result += root.`val` + } + result += rangeSumBST(root.left, low, high) + result += rangeSumBST(root.right, low, high) + } + + return result + } +} \ No newline at end of file diff --git a/2giwon/RecoverTree.kt b/2giwon/RecoverTree.kt new file mode 100644 index 0000000..c7b63ca --- /dev/null +++ b/2giwon/RecoverTree.kt @@ -0,0 +1,46 @@ +/** + * 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 RecoverTree { + private var prev: TreeNode? = null + private var first: TreeNode? = null + private var second: TreeNode? = null + + fun recoverTree(root: TreeNode?) { + + inOrder(root) + + val t = requireNotNull(first).`val` + first?.`val` = requireNotNull(second).`val` + second?.`val` = t + } + + private fun inOrder(root: TreeNode?) { + if (root == null) return + + inOrder(root.left) + + prev?.let { prev -> + if (prev.`val` > root.`val`) { + if (first == null) first = prev + second = root + } + } + + prev = root + inOrder(root.right) + } +} + +class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null +} \ No newline at end of file diff --git a/2giwon/SearchMatrix.kt b/2giwon/SearchMatrix.kt new file mode 100644 index 0000000..07b6e25 --- /dev/null +++ b/2giwon/SearchMatrix.kt @@ -0,0 +1,8 @@ +fun searchMatrix(matrix: Array, target: Int): Boolean { + if (matrix.isEmpty() || matrix[0].isEmpty()) return false + for (m in matrix) { + if (m.binarySearch(target, 0) >= 0) return true + } + + return false +} \ No newline at end of file diff --git a/2giwon/SpiralMatrix2.kt b/2giwon/SpiralMatrix2.kt new file mode 100644 index 0000000..e0057b2 --- /dev/null +++ b/2giwon/SpiralMatrix2.kt @@ -0,0 +1,43 @@ +class SpiralMatrix2 { + private lateinit var matrix: Array + private var number = 1 + + fun generateMatrix(n: Int): Array { + matrix = Array(n) { IntArray(n) { 0 } } + + val directions: Array> = arrayOf(0 to 1, 1 to 0, 0 to -1, -1 to 0) + var directionIndex = 0 + var col = 0 + var row = 0 + + matrix[col][row] = number++ + + while (true) { + if (number > n * n) break + while (true) { + val direction = directions[directionIndex] + if (row + direction.second !in 0 until n || col + direction.first !in 0 until n) break + + if (move(col + direction.first, row + direction.second)) { + col += direction.first + row += direction.second + } else { + break + } + } + + directionIndex = if (directionIndex + 1 >= directions.size) 0 else directionIndex + 1 + } + + return matrix + } + + private fun move(col: Int, row: Int): Boolean { + return if (matrix[col][row] == 0) { + matrix[col][row] = number++ + true + } else { + false + } + } +} \ No newline at end of file diff --git a/2giwon/SwapPairs.kt b/2giwon/SwapPairs.kt new file mode 100644 index 0000000..969cb98 --- /dev/null +++ b/2giwon/SwapPairs.kt @@ -0,0 +1,34 @@ +class SwapPairs { + private val list = mutableListOf() + + fun swapPairs(head: ListNode?): ListNode? { + if (head?.v == null) return head + req(head) + + for (i in list.indices) { + if (i % 2 > 0) { + val temp = list[i - 1] + list[i - 1] = list[i] + list[i] = temp + } + } + + return reqCreate(0, head) + } + + private fun reqCreate(index: Int, head: ListNode?): ListNode? { + if (index > list.lastIndex) { + return null + } + + val ret = ListNode(list[index]) + ret.next = reqCreate(index + 1, head?.next) + return ret + } + + private fun req(current: ListNode?) { + if (current == null) return + list.add(current.v ?: return) + req(current.next) + } +} \ 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/2giwon/src/Main.kt b/2giwon/src/Main.kt new file mode 100644 index 0000000..7d963d4 --- /dev/null +++ b/2giwon/src/Main.kt @@ -0,0 +1,3 @@ +fun main(args: Array) { + +} \ No newline at end of file diff --git a/2giwon/src/TapeEquilibrium.kt b/2giwon/src/TapeEquilibrium.kt new file mode 100644 index 0000000..ff55f83 --- /dev/null +++ b/2giwon/src/TapeEquilibrium.kt @@ -0,0 +1,20 @@ + +import kotlin.math.abs +import kotlin.math.min + +class TapeEquilibrium { + fun tapeEquilibrium(tape: IntArray): Int { + var front = 0 + val total = tape.sum() + var result = Int.MAX_VALUE + + for (p in 0 until tape.lastIndex) { + front += tape[p] + val end = total - front + result = min(result, abs(end - front)) + } + + + return result + } +} \ No newline at end of file diff --git a/2giwon/src/TargetNumber.kt b/2giwon/src/TargetNumber.kt new file mode 100644 index 0000000..1cde437 --- /dev/null +++ b/2giwon/src/TargetNumber.kt @@ -0,0 +1,20 @@ +class TargetNumber { + private var target = 0 + fun solution(numbers: IntArray, target: Int): Int { + this.target = target + return reqCal(numbers, 0, 0, 0) + } + + private fun reqCal(numbers: IntArray, i: Int, acc: Int, ans: Int): Int { + if (acc == target && i == numbers.size) return ans + 1 + if (i >= numbers.size) return ans + + var current = acc + numbers[i] + var answer = ans + reqCal(numbers, i + 1, current, ans) + + current = acc + (-numbers[i]) + answer += reqCal(numbers, i + 1, current, ans) + + return answer + } +} \ No newline at end of file diff --git a/2giwon/src/WordPattern.kt b/2giwon/src/WordPattern.kt new file mode 100644 index 0000000..5182426 --- /dev/null +++ b/2giwon/src/WordPattern.kt @@ -0,0 +1,23 @@ +import java.util.* + +class Solution { + fun wordPattern(pattern: String, s: String): Boolean { + val sList = s.split(" ") + val map = HashMap() + + if (sList.size != pattern.length) return false + for (i in sList.indices) { + if (map[pattern[i]] == null) { + if (map.containsValue(sList[i])) return false + map[pattern[i]] = sList[i] + } else { + if (map[pattern[i]] != sList[i]) { + return false + } + } + + } + + return true + } +} \ No newline at end of file diff --git a/2giwon/src/wordpattern/WordPattern.kt b/2giwon/src/wordpattern/WordPattern.kt new file mode 100644 index 0000000..54135e3 --- /dev/null +++ b/2giwon/src/wordpattern/WordPattern.kt @@ -0,0 +1,23 @@ +package wordpattern + +class Solution { + fun wordPattern(pattern: String, s: String): Boolean { + val sList = s.split(" ") + val map = HashMap() + + if (sList.size != pattern.length) return false + for (i in sList.indices) { + if (map[pattern[i]] == null) { + if (map.containsValue(sList[i])) return false + map[pattern[i]] = sList[i] + } else { + if (map[pattern[i]] != sList[i]) { + return false + } + } + + } + + return true + } +} \ No newline at end of file diff --git a/BeokBeok/Beautiful Arrangement.kt b/BeokBeok/Beautiful Arrangement.kt new file mode 100644 index 0000000..f32d7ad --- /dev/null +++ b/BeokBeok/Beautiful Arrangement.kt @@ -0,0 +1,25 @@ +class Solution { + var count = 0 + + fun countArrangement(n: Int): Int { + backtracking(n, 1, IntArray(size = n + 1)) + return count + } + + fun backtracking(n: Int, current: Int, visit: IntArray) { + if (current > n) { + count++ + return + } + + for (i in 1..n) { + val compareOne = current.rem(i) == 0 + val compareTwo = i.rem(current) == 0 + if (visit[i] == 0 && (compareOne || compareTwo)) { + visit[i] = 1 + backtracking(n, current + 1, visit) + visit[i] = 0 + } + } + } +} 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/ChocolatesByNumbers.kt b/BeokBeok/ChocolatesByNumbers.kt new file mode 100644 index 0000000..6ac8be7 --- /dev/null +++ b/BeokBeok/ChocolatesByNumbers.kt @@ -0,0 +1,8 @@ +fun solution(N: Int, M: Int): Int = N / gcd(N, M) + +fun gcd(a: Int, b: Int): Int { + val min = Math.min(a, b) + val max = Math.max(a, b) + + return if (min == 0) max else gcd(min, max % min) +} 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/Combination Sum.kt b/BeokBeok/Combination Sum.kt new file mode 100644 index 0000000..42cd7e8 --- /dev/null +++ b/BeokBeok/Combination Sum.kt @@ -0,0 +1,22 @@ +class Solution { + fun combinationSum(candidates: IntArray, target: Int): List> { + val result = mutableListOf>() + candidates.sort() + calculate(result, mutableListOf(), candidates, target, 0) + return result + } + + fun calculate(result: MutableList>, temp: MutableList, candidates: IntArray, target: Int, startIndex: Int) { + when { + target < 0 -> return + target == 0 -> result.add(temp.toList()) + else -> { + for (i in startIndex..candidates.lastIndex) { + temp.add(candidates[i]) + calculate(result, temp, candidates, target - candidates[i], i) + temp.removeAt(temp.lastIndex) + } + } + } + } +} 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/Decode String.kt b/BeokBeok/Decode String.kt new file mode 100644 index 0000000..3a893d9 --- /dev/null +++ b/BeokBeok/Decode String.kt @@ -0,0 +1,38 @@ +class Solution { + fun decodeString(s: String): String { + var result = "" + var index = 0 + val (strStack, countStack) = Stack() to Stack() + + while (index < s.length) { + when { + Character.isDigit(s[index]) -> { + var count = 0 + while (Character.isDigit(s[index])) { + count = count * 10 + (s[index] - '0') + index++ + } + countStack.push(count) + } + s[index] == '[' -> { + strStack.push(result) + result = "" + index++ + } + s[index] == ']' -> { + var temp = strStack.pop() + repeat(countStack.pop()) { + temp += result + } + result = temp + index++ + } + else -> { + result += s[index++] + } + } + } + + return result + } +} diff --git a/BeokBeok/Delete Node in a BST.kt b/BeokBeok/Delete Node in a BST.kt new file mode 100644 index 0000000..8db7467 --- /dev/null +++ b/BeokBeok/Delete Node in a BST.kt @@ -0,0 +1,34 @@ +/** + * 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 deleteNode(root: TreeNode?, key: Int): TreeNode? { + when { + root == null -> return root + root.`val` > key -> root.left = deleteNode(root.left, key) + root.`val` < key -> root.right = deleteNode(root.right, key) + else -> { + when { + root.left == null -> return root.right + root.right == null -> return root.left + else -> { + var minTarget = root.right + while (minTarget?.left != null) { + minTarget = minTarget.left + } + root.`val` = minTarget?.`val` ?: 0 + root.right = deleteNode(root.right, root.`val`) + } + } + } + } + return root + } +} 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 Smallest Divisor Given a Threshold.kt b/BeokBeok/Find the Smallest Divisor Given a Threshold.kt new file mode 100644 index 0000000..7ac1d97 --- /dev/null +++ b/BeokBeok/Find the Smallest Divisor Given a Threshold.kt @@ -0,0 +1,18 @@ +class Solution { + fun smallestDivisor(nums: IntArray, threshold: Int): Int { + nums.sort() + var (min, max) = 1 to nums.last() + while (min < max) { + val mid = (min + max) / 2 + val sum = nums + .asSequence() + .map(Int::toDouble) + .fold(0.0) { acc, i -> + acc + (Math.ceil(i.div(mid.toDouble()))) + } + .toInt() + if (sum > threshold) min = mid + 1 else max = mid + } + return min + } +} 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/Increasing Order Search Tree.kt b/BeokBeok/Increasing Order Search Tree.kt new file mode 100644 index 0000000..f4bae09 --- /dev/null +++ b/BeokBeok/Increasing Order Search Tree.kt @@ -0,0 +1,22 @@ +/** + * 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 increasingBST(root: TreeNode?): TreeNode? = + build(root, null) + + fun build(target: TreeNode?, before: TreeNode?): TreeNode? { + if (target == null) return before + val result = build(target.left, target) + target.left = null + target.right = build(target.right, before) + return result + } +} 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/Palindrome Partitioning.kt b/BeokBeok/Palindrome Partitioning.kt new file mode 100644 index 0000000..6b54042 --- /dev/null +++ b/BeokBeok/Palindrome Partitioning.kt @@ -0,0 +1,37 @@ +class Solution { + val result = mutableListOf>() + val current = mutableListOf() + + fun partition(s: String): List> { + backTrack(s, 0) + return result.toList() + } + + fun backTrack(s: String, l: Int) { + if (current.size > 0 && l >= s.length) { + result.add(current.toList()) + } + for (i in l..s.lastIndex) { + if (isPalindrome(s, l, i)) { + if (l == i) { + current.add(s[i].toString()) + } else { + current.add(s.substring(l, i + 1)) + } + backTrack(s, i + 1) + current.removeAt(current.lastIndex) + } + } + } + + fun isPalindrome(s: String, l: Int, i: Int): Boolean { + var (length, index) = l to i + if (length == index) return true + while (length < index) { + if (s[length] != s[index]) return false + length++ + index-- + } + return true + } +} 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/Permutations II.kt b/BeokBeok/Permutations II.kt new file mode 100644 index 0000000..e94fbac --- /dev/null +++ b/BeokBeok/Permutations II.kt @@ -0,0 +1,27 @@ +class Solution { + val result = mutableListOf>() + val visit = mutableMapOf() + val temp = mutableListOf() + + fun permuteUnique(nums: IntArray): List> { + if (nums.size == 1) return listOf(nums.toList()) + doDFS(nums.sorted()) + return result.distinct() + } + + fun doDFS(nums: List) { + if (nums.size == temp.size) { + result.add(temp.toList()) + return + } + for (i in nums.indices) { + if (!visit.containsKey(i)) visit.computeIfAbsent(i) { false } + if (visit[i] == true) continue + visit[i] = true + temp.add(nums[i]) + doDFS(nums) + visit[i] = false + temp.removeAt(temp.lastIndex) + } + } +} diff --git a/BeokBeok/README.md b/BeokBeok/README.md index 903be3c..8ce397e 100644 --- a/BeokBeok/README.md +++ b/BeokBeok/README.md @@ -1 +1,2 @@ # BeokBeok 의 저장소 + diff --git a/BeokBeok/Range Sum of BST.kt b/BeokBeok/Range Sum of BST.kt new file mode 100644 index 0000000..504cf8c --- /dev/null +++ b/BeokBeok/Range Sum of BST.kt @@ -0,0 +1,10 @@ +class Solution { + fun rangeSumBST(root: TreeNode?, low: Int, high: Int): Int { + if (root == null) return 0 + var sum = 0 + if (root.`val` > low) sum += rangeSumBST(root.left, low, high) + if (root.`val` < high) sum += rangeSumBST(root.right, low, high) + if (root.`val` in low..high) sum += root.`val` + return sum + } +} diff --git a/BeokBeok/Recover Binary Search Tree.kt b/BeokBeok/Recover Binary Search Tree.kt new file mode 100644 index 0000000..e4c9a2b --- /dev/null +++ b/BeokBeok/Recover Binary Search Tree.kt @@ -0,0 +1,42 @@ +/** + * 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 swappedFirstNode: TreeNode? = null + var swappedSecondNode: TreeNode? = null + var prevNode: TreeNode = TreeNode(Int.MIN_VALUE) + + fun recoverTree(root: TreeNode?): Unit { + if (root == null) return + + doDFS(root) + + val temp = swappedFirstNode?.`val` ?: Int.MIN_VALUE + swappedFirstNode?.`val` = swappedSecondNode?.`val` ?: Int.MIN_VALUE + swappedSecondNode?.`val` = temp + } + + private fun doDFS(root: TreeNode?) { + if (root == null) return + + doDFS(root.left) + + if (swappedFirstNode == null && prevNode.`val` > root.`val`) { + swappedFirstNode = prevNode + } + + if (swappedFirstNode != null && prevNode.`val` > root.`val`) { + swappedSecondNode = root + } + prevNode = root + + doDFS(root.right) + } +} 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/Search a 2D Matrix.kt b/BeokBeok/Search a 2D Matrix.kt new file mode 100644 index 0000000..1229379 --- /dev/null +++ b/BeokBeok/Search a 2D Matrix.kt @@ -0,0 +1,6 @@ +class Solution { + fun searchMatrix(matrix: Array, target: Int): Boolean = matrix + .map(IntArray::toList) + .flatten() + .binarySearch(target) > -1 +} 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/Spiral Matrix II.kt b/BeokBeok/Spiral Matrix II.kt new file mode 100644 index 0000000..ffc749f --- /dev/null +++ b/BeokBeok/Spiral Matrix II.kt @@ -0,0 +1,39 @@ +class Solution { + fun generateMatrix(n: Int): Array { + if (n == 0) return emptyArray() + + val matrix = Array(n) { + IntArray(n) { 0 } + } + + var (rowStart, rowEnd) = 0 to n - 1 + var (colStart, colEnd) = 0 to n - 1 + var num = 1 + + while (rowStart <= rowEnd && colStart <= colEnd) { + for (i in colStart..colEnd) { + matrix[rowStart][i] = num++ + } + rowStart++ + + for (i in rowStart..rowEnd) { + matrix[i][colEnd] = num++ + } + colEnd-- + + for (i in colEnd downTo colStart) { + if (rowStart > rowEnd) break + matrix[rowEnd][i] = num++ + } + rowEnd-- + + for (i in rowEnd downTo rowStart) { + if (colStart > colEnd) break + matrix[i][colStart] = num++ + } + colStart++ + } + + return matrix + } +} diff --git a/BeokBeok/SumVsXor.kt b/BeokBeok/SumVsXor.kt new file mode 100644 index 0000000..f88eedf --- /dev/null +++ b/BeokBeok/SumVsXor.kt @@ -0,0 +1,8 @@ +fun sumXor(n: Long): Long { + var (target, result) = n to 0L + while (target > 0) { + result += if (target.rem(2) == 0L) 1L else 0L + target /= 2 + } + return Math.pow(2.0, result.toDouble()).toLong() +} diff --git a/BeokBeok/Swap Nodes in Pairs.kt b/BeokBeok/Swap Nodes in Pairs.kt new file mode 100644 index 0000000..84875d5 --- /dev/null +++ b/BeokBeok/Swap Nodes in Pairs.kt @@ -0,0 +1,19 @@ +/** + * 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 swapPairs(head: ListNode?): ListNode? { + if (head?.next == null) return head + + val temp = head.next + head.next = swapPairs(head.next?.next) + temp?.next = head + return temp + } +} diff --git a/BeokBeok/TapeEquilibrium.kt b/BeokBeok/TapeEquilibrium.kt new file mode 100644 index 0000000..b722e70 --- /dev/null +++ b/BeokBeok/TapeEquilibrium.kt @@ -0,0 +1,12 @@ +fun solution(A: IntArray): Int { + val total = A.sum() + var (leftSum, rightSum) = A[0] to total - A[0] + if (A.size == 1) return A[0] + var result = Int.MAX_VALUE + for (i in 1..A.lastIndex) { + result = result.coerceAtMost(Math.abs(leftSum - rightSum)) + leftSum += A[i] + rightSum -= A[i] + } + return result +} diff --git a/BeokBeok/TargetNumber.kt b/BeokBeok/TargetNumber.kt new file mode 100644 index 0000000..143d6db --- /dev/null +++ b/BeokBeok/TargetNumber.kt @@ -0,0 +1,12 @@ +class Solution { + fun solution(numbers: IntArray, target: Int): Int { + fun calculateSum(index: Int, target: Int, sum: Int): Int { + if (index > numbers.lastIndex) { + return if (target == sum) 1 else 0 + } + return calculateSum(index + 1, target, sum + numbers[index]) + + calculateSum(index + 1, target, sum - numbers[index]) + } + return calculateSum(0, target, 0) + } +} 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/BeokBeok/Word Pattern.kt b/BeokBeok/Word Pattern.kt new file mode 100644 index 0000000..f032e20 --- /dev/null +++ b/BeokBeok/Word Pattern.kt @@ -0,0 +1,13 @@ +class Solution { + fun wordPattern(pattern: String, s: String): Boolean { + val (patternToCharArr, sToSplitList) = pattern.toCharArray() to s.split(" ") + if (patternToCharArr.size != sToSplitList.size) return false + val patternToSMap = mutableMapOf() + patternToCharArr.forEachIndexed { index, char -> + patternToSMap.computeIfAbsent(char) { sToSplitList[index] } + if (!patternToSMap.containsKey(char)) return@forEachIndexed + if (patternToSMap[char] != sToSplitList[index]) return false + } + return patternToCharArr.distinct().size == patternToSMap.values.distinct().size + } +} diff --git a/CmplxN/ChocolatesByNumbers.kt b/CmplxN/ChocolatesByNumbers.kt new file mode 100644 index 0000000..32f5bb6 --- /dev/null +++ b/CmplxN/ChocolatesByNumbers.kt @@ -0,0 +1,14 @@ +// you can also use imports, for example: +// import kotlin.math.* + +// you can write to stdout for debugging purposes, e.g. +// println("this is a debug message") + +fun solution(N: Int, M: Int): Int = N / gcd(N, M) + +tailrec fun gcd(a: Int, b: Int): Int { + return when (val r = a % b) { + 0 -> b + else -> gcd(b, r) + } +} diff --git a/CmplxN/CombinationSum.kt b/CmplxN/CombinationSum.kt new file mode 100644 index 0000000..3c09a68 --- /dev/null +++ b/CmplxN/CombinationSum.kt @@ -0,0 +1,22 @@ +class Solution { + fun combinationSum(candidates: IntArray, target: Int): List> { + val sortedCandidates = candidates.sorted() + val rtn = mutableListOf>() + val temp = mutableListOf() + fun dfs(sum: Int, idx: Int) { + if (sum == target) { + rtn.add(temp.map { it }) + return + } + for (i in idx..sortedCandidates.lastIndex) { + val pick = sortedCandidates[i] + if (sum + pick > target) return + temp.add(pick) + dfs(sum + pick, i) + temp.removeAt(temp.lastIndex) + } + } + dfs(0, 0) + return rtn + } +} diff --git a/CmplxN/README.md b/CmplxN/README.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/CmplxN/README.md @@ -0,0 +1 @@ + diff --git a/CmplxN/Search_a_2D_Matrix.kt b/CmplxN/Search_a_2D_Matrix.kt new file mode 100644 index 0000000..5b80aad --- /dev/null +++ b/CmplxN/Search_a_2D_Matrix.kt @@ -0,0 +1,3 @@ +class Solution { + fun searchMatrix(matrix: Array, target: Int) = matrix.map { it.toList() }.flatten().binarySearch(target) >= 0 +} diff --git a/LeePoongHo/2dMarix.java b/LeePoongHo/2dMarix.java new file mode 100644 index 0000000..c5c522a --- /dev/null +++ b/LeePoongHo/2dMarix.java @@ -0,0 +1,12 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + for(int i=0; i key) { + root.left = deleteNode(root.left, key) + } + else if (root.`val` < key) { + root.right = deleteNode(root.right, key) + } + else { + if (root.left == null) { + return root.right + } else if (root.right == null) { + return root.left + } + + val min = searchMin(root.right) + if (min != null) { + root.`val` = min.`val` + root.right = deleteNode(root.right, min.`val`) + } + } + return root + } + + fun searchMin(node: TreeNode?): TreeNode? { + if (node == null) return null + return if (node.left == null) node + else searchMin(node.left) + } +} \ No newline at end of file diff --git a/improve777/FindTheSmallestDivisorGivenAThreshold.kt b/improve777/FindTheSmallestDivisorGivenAThreshold.kt new file mode 100644 index 0000000..1a48a4f --- /dev/null +++ b/improve777/FindTheSmallestDivisorGivenAThreshold.kt @@ -0,0 +1,22 @@ +class Solution { + fun smallestDivisor(nums: IntArray, threshold: Int): Int { + var end = 2 + while (computeSum(nums, end) > threshold) end = end shl 1 + + var start = end shr 1 + while (start < end) { + val mid = start + (end - start) / 2 + if (computeSum(nums, mid) > threshold) start = mid + 1 + else end = mid + } + return start + } + + private fun computeSum(nums: IntArray, i: Int): Long { + var sum = 0L + for (num in nums) { + sum += if (num % i == 0) num / i else num / i + 1 + } + return sum + } +} 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/Permutations2.kt b/improve777/Permutations2.kt new file mode 100644 index 0000000..a628c07 --- /dev/null +++ b/improve777/Permutations2.kt @@ -0,0 +1,24 @@ +class Solution { + fun permuteUnique(nums: IntArray): List> { + if (nums.size == 1) return listOf(nums.toList()) + + val result = mutableSetOf>() + val list = nums.toMutableList() + + fun _permuteUnique(loop: MutableList, acc: MutableList) { + if (loop.isEmpty()) result.add(acc) + + for (i in loop) { + val copy = loop.toMutableList() + copy.remove(i) + val added = acc.toMutableList().apply { add(i) } + _permuteUnique(copy, added) + } + if (loop.isEmpty()) result.add(acc) + } + + _permuteUnique(list, mutableListOf()) + + return result.toList() + } +} diff --git a/improve777/README.md b/improve777/README.md new file mode 100644 index 0000000..0c01a25 --- /dev/null +++ b/improve777/README.md @@ -0,0 +1 @@ +# improve777 의 저장소 \ No newline at end of file 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 diff --git a/improve777/Searcha2DMatrix.kt b/improve777/Searcha2DMatrix.kt new file mode 100644 index 0000000..dc05ab7 --- /dev/null +++ b/improve777/Searcha2DMatrix.kt @@ -0,0 +1,12 @@ +class Solution { + fun searchMatrix(matrix: Array, target: Int): Boolean { + matrix.forEach { + if (it.isNotEmpty()) { + if (target <= it[it.lastIndex]) { + return it.contains(target) + } + } + } + return false + } +} diff --git a/improve777/TapeEquilibrium.kt b/improve777/TapeEquilibrium.kt new file mode 100644 index 0000000..40f80ec --- /dev/null +++ b/improve777/TapeEquilibrium.kt @@ -0,0 +1,17 @@ +import kotlin.math.abs + +private fun solution(A: IntArray): Int { + var beforeP = 0 + var afterP = A.sum() + var min = Int.MAX_VALUE + + for (i in 0 until A.size - 1) { + beforeP += A[i] + afterP -= A[i] + val n = abs(beforeP - afterP) + if (min > n) { + min = n + } + } + return min +} diff --git a/namjackson/CombinationSum.kt b/namjackson/CombinationSum.kt new file mode 100644 index 0000000..6f08b94 --- /dev/null +++ b/namjackson/CombinationSum.kt @@ -0,0 +1,29 @@ +class Solution { + fun combinationSum(candidates: IntArray, target: Int): List> { + val resultList = mutableListOf>() + search(candidates.sortedArrayDescending(), target, intArrayOf(), resultList) + return resultList.distinct() + } + + private fun search( + candidates: IntArray, + target: Int, + sumArray: IntArray, + resultList: MutableList> + ) { + val sum = sumArray.sum() + candidates.forEach { num -> + val gap = target - (sum + num) + when { + (gap == 0) -> { + val list = sumArray.toMutableList().also { it.add(num) } + resultList.add(list.sorted()) + } + (gap > 0) -> { + val list = sumArray.toMutableList().also { it.add(num) } + search(candidates, target, list.toIntArray(), resultList) + } + } + } + } +} \ No newline at end of file diff --git a/namjackson/TapeEquilibrium.kt b/namjackson/TapeEquilibrium.kt new file mode 100644 index 0000000..770ca26 --- /dev/null +++ b/namjackson/TapeEquilibrium.kt @@ -0,0 +1,13 @@ +import kotlin.math.abs + +fun solution(A: IntArray): Int { + var minimum = Int.MAX_VALUE + var firstPart = 0 + var secondPart = A.sum() + (0 until A.lastIndex).forEach { + firstPart += A[it] + secondPart -= A[it] + minimum = abs(firstPart - secondPart).takeIf { it < minimum } ?: minimum + } + return minimum +} \ No newline at end of file diff --git a/namjackson/TargetNumber.kt b/namjackson/TargetNumber.kt new file mode 100644 index 0000000..37269b4 --- /dev/null +++ b/namjackson/TargetNumber.kt @@ -0,0 +1,16 @@ +class Solution { + fun solution(numbers: IntArray, target: Int): Int { + return search(numbers, target, 0, 0) + } + + private fun search(numbers: IntArray, target: Int, index: Int, sum: Int): Int { + return when { + index < numbers.size -> { + val plusCount = search(numbers, target, index + 1, sum + numbers[index]) + val minusCount = search(numbers, target, index + 1, sum - numbers[index]) + plusCount + minusCount + } + else -> if (sum == target) 1 else 0 + } + } +} diff --git a/sjjeong/CombinationSum.kt b/sjjeong/CombinationSum.kt new file mode 100644 index 0000000..dfbf9e5 --- /dev/null +++ b/sjjeong/CombinationSum.kt @@ -0,0 +1,42 @@ +class Solution { + fun combinationSum(candidates: IntArray, target: Int): List> { + return generateResult(candidates.toList(), target).filter { it.sum() == target } + } + + private fun generateResult(candidates: List, target: Int): List> { + return candidates.takeIf { it.isNotEmpty() }?.run { + flatMapIndexed { index: Int, num: Int -> + when { + target < num -> { + listOf(listOf()) + } + target == num -> { + listOf(listOf(target)) + } + else -> { + generateResult(candidates.drop(index), target - num).map { + it.toMutableList() + .apply { + add(0, num) + } + } + } + } + } + }?: listOf(listOf()) + } + + private inline fun Iterable.flatMapIndexed(transform: (index: Int, T) -> Iterable): List { + return flatMapIndexedTo(ArrayList(), transform) + } + + private inline fun > Iterable.flatMapIndexedTo(destination: C, transform: (index: Int, T) -> Iterable): C { + var index = 0 + for (element in this) { + val list = transform(index++, element) + destination.addAll(list) + } + return destination + } + +} diff --git a/sjjeong/TapeEquilibrium.kt b/sjjeong/TapeEquilibrium.kt new file mode 100644 index 0000000..7afe681 --- /dev/null +++ b/sjjeong/TapeEquilibrium.kt @@ -0,0 +1,13 @@ +fun solution(A: IntArray): Int { + var sum = A.sum() - A[0] + var min = Int.MAX_VALUE + A.reduce { acc, i -> + val absoluteValue = (acc - sum).absoluteValue + if (absoluteValue < min) { + min = absoluteValue + } + sum -= i + acc + i + } + return min +} \ No newline at end of file diff --git a/sjjeong/TargetNumber.kt b/sjjeong/TargetNumber.kt new file mode 100644 index 0000000..ce04ba1 --- /dev/null +++ b/sjjeong/TargetNumber.kt @@ -0,0 +1,19 @@ +class Solution { + fun solution(numbers: IntArray, target: Int): Int { + val diff = (numbers.sum() - target) / 2 + return find(numbers, diff, 0, numbers.size) + } + + fun find(numbers: IntArray, diff: Int, index: Int, size: Int): Int { + var answer = 0 + for (i in index until size) { + val number = numbers[i] + if (number == diff) { + answer++ + } else if (number < diff) { + answer += find(numbers, diff - number, i + 1, size) + } + } + return answer + } +} \ No newline at end of file diff --git a/sjjeong/WordPattern.kt b/sjjeong/WordPattern.kt new file mode 100644 index 0000000..21ca3de --- /dev/null +++ b/sjjeong/WordPattern.kt @@ -0,0 +1,28 @@ +class Solution { + + fun wordPattern(pattern: String, s: String): Boolean { + var remainText = s + val patternMap = mutableMapOf() + pattern.forEach { + if (remainText.isEmpty()) { + return false + } + val index = remainText.indexOf(' ') + val str = if (index == -1) remainText else remainText.substring(0, index) + + val value = patternMap[it] + if (value == null && !patternMap.values.contains(str)) { + patternMap[it] = str + } else { + if (value != str) { + return false + } + } + remainText = if (index == -1) "" else remainText.substring(index + 1, remainText.length) + } + if (remainText.isNotEmpty()) { + return false + } + return true + } +} \ No newline at end of file