From 64b4d79303f997fbd4d06dba5d2f2fec7492e07f Mon Sep 17 00:00:00 2001 From: Xiang LI Date: Sun, 26 Jul 2020 23:06:42 +0200 Subject: [PATCH] add kotlin solutions --- .../Angle-Between-Hands-of-a-Clock.kt | 35 ++++++ .../Reverse-Words-in-a-String.kt | 45 ++++++++ .../16-Pow(x,n)/Pow(x,n).kt | 31 ++++++ .../Top-K-Frequent-Elements.kt | 16 +++ .../Course-Schedule-II.kt | 75 +++++++++++++ .../19-Add-Binary/Add-Binary.kt | 61 +++++++++++ .../Remove-Linked-List-Elements.kt | 55 ++++++++++ .../21-Word-Search/Word-Search.kt | 102 ++++++++++++++++++ ...inary-Tree-Zigzag-Level-Order-Traversal.kt | 36 +++++++ .../23-Single-Number-III/Single-Number-III.kt | 18 ++++ .../All-Paths-From-Source-to-Target.kt | 44 ++++++++ ...Find-Minimum-in-Rotated-Sorted-Array-II.kt | 24 +++++ .../26-Add-Digits/Add-Digits.kt | 31 ++++++ 13 files changed, 573 insertions(+) create mode 100644 July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt create mode 100644 July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt create mode 100644 July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt create mode 100644 July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt create mode 100644 July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt create mode 100644 July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt create mode 100644 July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt create mode 100644 July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt create mode 100644 July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt create mode 100644 July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt create mode 100644 July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt create mode 100644 July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt create mode 100644 July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt diff --git a/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt new file mode 100644 index 0000000..614ae40 --- /dev/null +++ b/July-LeetCoding-Challenge/14-Angle-Between-Hands-of-a-Clock/Angle-Between-Hands-of-a-Clock.kt @@ -0,0 +1,35 @@ +package string_integer + +import kotlin.math.abs + +class AngleBetweenHandsofaClockKotlin1344 { + fun angleClock(hour: Int, minutes: Int): Double { + val baseHour = when (hour) { + 12 -> 0 + else -> 30 * hour + } + val hourVal = minutes.toDouble() / 2 + baseHour + + val minutesVal = minutes.toDouble() * 6 + + val result = abs(hourVal - minutesVal) + + return if (result > 180) 360 - result else result + } +} + +fun main() { + val solution = AngleBetweenHandsofaClockKotlin1344() + // 165 + println(solution.angleClock(12, 30)) + // 75 + println(solution.angleClock(3, 30)) + // 7.5 + println(solution.angleClock(3, 15)) + // 155 + println(solution.angleClock(4, 50)) + // 0 + println(solution.angleClock(12, 0)) + // 76.5 + println(solution.angleClock(1, 57)) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt b/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt new file mode 100644 index 0000000..57bea8e --- /dev/null +++ b/July-LeetCoding-Challenge/15-Reverse-Words-in-a-String/Reverse-Words-in-a-String.kt @@ -0,0 +1,45 @@ +package string_integer + +class ReverseWordsinaStringKotlin151 { + fun reverseWords(s: String): String = + s.trim() + .split("\\s+".toRegex()) + .reversed() + .joinToString(separator = " ") + /* + fun reverseWords(s: String): String { + val list: MutableList = LinkedList() + var index = 0 + while (index < s.length) { + if (s[index] == ' ') { + ++index + } else { + val stringBuilder = StringBuilder() + while (index < s.length && s[index] != ' ') { + stringBuilder.append(s[index]) + ++index + } + list.add(stringBuilder.toString()) + } + } + val result = StringBuilder() + for (i in list.size - 1 downTo 0) { + result.append(list[i]) + if (i != 0){ + result.append(" ") + } + } + return result.toString() + } + */ +} + +fun main() { + val solution = ReverseWordsinaString151() + // blue is sky the + println(solution.reverseWords("the sky is blue")) + // world! hello + println(solution.reverseWords(" hello world! ")) + // example good a + println(solution.reverseWords("a good example")) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt b/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt new file mode 100644 index 0000000..e18364d --- /dev/null +++ b/July-LeetCoding-Challenge/16-Pow(x,n)/Pow(x,n).kt @@ -0,0 +1,31 @@ +package binary_search + +class PowxnKotlin50 { + fun myPow(x: Double, n: Int): Double { + return when { + x == 0.0 -> 0.0 + n == 1 -> x + n == -1 -> 1 / x + n == 0 -> 1.0 + // Int.MIN_VALUE = Int.MAX_VALUE + 1 + n == Int.MIN_VALUE -> 1 / powLog(x, Int.MAX_VALUE) * x + n > 0 -> powLog(x, n) + n < 0 -> 1 / powLog(x, -n) + else -> -1.0 + } + } + + private fun powLog(x: Double, n: Int): Double = + when { + n == 1 -> x + n % 2 == 0 -> { + val result = powLog(x, n.shr(1)) + result * result + } + n % 2 == 1 -> { + val result = powLog(x, n.shr(1)) + result * result * x + } + else -> -1.0 + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt b/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt new file mode 100644 index 0000000..9093960 --- /dev/null +++ b/July-LeetCoding-Challenge/17-Top-K-Frequent-Elements/Top-K-Frequent-Elements.kt @@ -0,0 +1,16 @@ +package list_array + +class TopKFrequentElementsKotlin347 { + fun topKFrequent(nums: IntArray, k: Int): IntArray { + val map: MutableMap = HashMap() + nums.forEach { + map[it] = map.getOrDefault(it, 0) + 1 + } + return map + .toList() + .sortedByDescending(Pair::second) + .subList(0, k) + .map { it.first } + .toIntArray() + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt new file mode 100644 index 0000000..76fde3e --- /dev/null +++ b/July-LeetCoding-Challenge/18-Course-Schedule-II/Course-Schedule-II.kt @@ -0,0 +1,75 @@ +package graph + +class CourseScheduleKotlin207 { + fun canFinish(numCourses: Int, prerequisites: Array): Boolean { + // 1 true, -1 false, 0 not judge + val coursesArray = IntArray(numCourses) + val graph: MutableMap> = HashMap() + for (pre in prerequisites) { + graph.computeIfAbsent(pre[1]) { mutableListOf() }.add(pre[0]) + } + for (index in coursesArray.indices) { + if (!dfs(index, coursesArray, graph)) { + return false + } + } + return true + } + + // true -> can finish + private fun dfs( + current: Int, + coursesArray: IntArray, + graph: Map> + ): Boolean { + return when { + coursesArray[current] == -1 -> false + coursesArray[current] == 1 -> true + else -> { + coursesArray[current] = -1 + graph[current]?.forEach { + if (!dfs(it, coursesArray, graph)) { + return false + } + } + coursesArray[current] = 1 + true + } + } + } + /* + fun canFinish(numCourses: Int, prerequisites: Array): Boolean { + val coursesArray = IntArray(numCourses) + val graph: MutableMap> = HashMap() + for (pre in prerequisites) { + graph.computeIfAbsent(pre[1]) { mutableListOf() }.add(pre[0]) + ++coursesArray[pre[0]] + } + val queue: Queue = LinkedList() + coursesArray.forEachIndexed { index, i -> + if (i == 0) { + queue.offer(index) + } + } + while (queue.isNotEmpty()) { + val current = queue.poll() + graph[current]?.forEach { + if (--coursesArray[it] == 0) { + queue.offer(it) + } + } + } + return coursesArray.count { it == 0 } == numCourses + } + */ +} + +fun main() { + val solution = CourseScheduleKotlin207() + // true + println(solution.canFinish(2, arrayOf(intArrayOf(0, 1)))) + // false + println(solution.canFinish(2, arrayOf(intArrayOf(0, 1), intArrayOf(1, 0)))) + // true + println(solution.canFinish(3, arrayOf(intArrayOf(2, 1), intArrayOf(1, 0)))) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt new file mode 100644 index 0000000..a1d29c3 --- /dev/null +++ b/July-LeetCoding-Challenge/19-Add-Binary/Add-Binary.kt @@ -0,0 +1,61 @@ +package string_integer + +class AddBinaryKotlin67 { + fun addBinary(a: String, b: String): String { + if (a.length > b.length) { + return addBinary(b, a) + } + val diff = b.length - a.length + var next = 0 + val result = StringBuilder() + for (index in a.length - 1 downTo 0) { + val currentA = a[index].toString().toInt() + val currentB = b[index + diff].toString().toInt() + when (next + currentA + currentB) { + 0 -> result.append(0) + 1 -> { + result.append(1) + next = 0 + } + 2 -> { + result.append(0) + next = 1 + } + 3 -> { + result.append(1) + next = 1 + } + } + } + for (index in diff - 1 downTo 0) { + val currentB = b[index].toString().toInt() + when (currentB + next) { + 0 -> result.append(0) + 1 -> { + result.append(1) + next = 0 + } + 2 -> { + result.append(0) + next = 1 + } + } + } + if (next == 1) { + result.append(next) + } + return result.reverse().toString() + } +} + +fun main() { + val solution = AddBinaryKotlin67() + // 100 + println(solution.addBinary("11", "1")) + // 10101 + println(solution.addBinary("1010", "1011")) + // 1100 + println(solution.addBinary("1011", "1")) + // 1110 + println(solution.addBinary("1011", "11")) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt new file mode 100644 index 0000000..cb58b1b --- /dev/null +++ b/July-LeetCoding-Challenge/20-Remove-Linked-List-Elements/Remove-Linked-List-Elements.kt @@ -0,0 +1,55 @@ +package list_array + +class RemoveLinkedListElementsKotlin203 { + class ListNode(var `val`: Int) { + var next: ListNode? = null + } + + fun removeElements(head: ListNode?, `val`: Int): ListNode? { + if (head == null) { + return null + } + if (head.`val` == `val`) { + return removeElements(head.next, `val`) + } + head.next = removeElements(head.next, `val`) + return head + } + /* + fun removeElements(head: ListNode?, `val`: Int): ListNode? { + var current: ListNode? = head ?: return head + while (current != null && current.`val` == `val`) { + current = current.next + } + val result = current + var previous = current + current = current?.next + while (current != null) { + if (current.`val` == `val`) { + while (current != null && current.`val` == `val`) { + current = current.next + } + previous!!.next = current + } + previous = current + current = current?.next + } + return result + } + */ +} + +fun main() { + val solution = RemoveLinkedListElementsKotlin203() + val l1 = RemoveLinkedListElementsKotlin203.ListNode(1) + val l2 = RemoveLinkedListElementsKotlin203.ListNode(2) + val l22 = RemoveLinkedListElementsKotlin203.ListNode(2) + val l12 = RemoveLinkedListElementsKotlin203.ListNode(1) + + l1.next = l2 + l2.next = l22 + l22.next = l12 + + val result = solution.removeElements(l1, 2) + println(result) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt b/July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt new file mode 100644 index 0000000..d103ca4 --- /dev/null +++ b/July-LeetCoding-Challenge/21-Word-Search/Word-Search.kt @@ -0,0 +1,102 @@ +package depth_first_search + +class WordSearchKotlin79 { + var result = false + + fun exist(board: Array, word: String): Boolean { + result = false + for (x in board.indices) { + for (y in board[0].indices) { + if (result) { + return true + } + if (board[x][y] == word[0]) { + dfs(board, x, y, word, 0) + } + } + } + return result + } + + private val deltaX = intArrayOf(0, 0, -1, 1) + private val deltaY = intArrayOf(-1, 1, 0, 0) + + private fun dfs(board: Array, x: Int, y: Int, word: String, current: Int) { + if (current == word.length - 1) { + result = true + return + } + val value = board[x][y] + board[x][y] = '*' + for (index in deltaX.indices) { + val nextX = x + deltaX[index] + val nextY = y + deltaY[index] + if (inBound(board, nextX, nextY) && board[nextX][nextY] == word[current + 1] && !result) { + dfs(board, nextX, nextY, word, current + 1) + } + } + board[x][y] = value + } + + private fun inBound( + grid: Array, + x: Int, + y: Int + ) = x >= 0 && y >= 0 && x < grid.size && y < grid[0].size + /* + fun exist(board: Array, word: String): Boolean { + for (x in board.indices) { + for (y in board[0].indices) { + if (board[x][y] == word[0]) { + if (dfs(board, x, y, word, 0)) { + return true + } + } + } + } + return false + } + + private val deltaX = intArrayOf(0, 0, -1, 1) + private val deltaY = intArrayOf(-1, 1, 0, 0) + + private fun dfs(board: Array, x: Int, y: Int, word: String, current: Int): Boolean { + if (current == word.length - 1) { + return true + } + val value = board[x][y] + board[x][y] = '*' + var result = false + for (index in deltaX.indices) { + val nextX = x + deltaX[index] + val nextY = y + deltaY[index] + if (inBound(board, nextX, nextY) && board[nextX][nextY] == word[current + 1] && !result) { + if (dfs(board, nextX, nextY, word, current + 1)) { + result = true + } + } + } + board[x][y] = value + return result + } + + private fun inBound( + grid: Array, + x: Int, + y: Int + ) = x >= 0 && y >= 0 && x < grid.size && y < grid[0].size + */ +} + +fun main() { + val test = arrayOf( + charArrayOf('A', 'B', 'C', 'E'), + charArrayOf('S', 'F', 'C', 'S'), + charArrayOf('A', 'D', 'E', 'E') + ) + val solution = WordSearchKotlin79() + // true true false + println(solution.exist(test, "ABCCED")) + println(solution.exist(test, "SEE")) + println(solution.exist(test, "ABCB")) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt new file mode 100644 index 0000000..d5efca2 --- /dev/null +++ b/July-LeetCoding-Challenge/22-Binary-Tree-Zigzag-Level-Order-Traversal/Binary-Tree-Zigzag-Level-Order-Traversal.kt @@ -0,0 +1,36 @@ +package breadth_first_search + +import java.util.* + +class BinaryTreeZigzagLevelOrderTraversalKotlin103 { + fun zigzagLevelOrder(root: TreeNode?): List> { + val result = mutableListOf>() + if (root == null) { + return result + } + val treeNodeQueue: Queue = LinkedList() + treeNodeQueue.offer(root) + var flag = false + while (treeNodeQueue.isNotEmpty()) { + val currentLevel = mutableListOf() + for (i in 0 until treeNodeQueue.size) { + val current = treeNodeQueue.poll() + if (flag) { + currentLevel.add(0, current.`val`) + } else { + currentLevel.add(current.`val`) + } + current.left?.let { treeNodeQueue.offer(it) } + current.right?.let { treeNodeQueue.offer(it) } + } + result.add(currentLevel) + flag = !flag + } + return result + } + + class TreeNode(var `val`: Int) { + var left: TreeNode? = null + var right: TreeNode? = null + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt b/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt new file mode 100644 index 0000000..68a29b0 --- /dev/null +++ b/July-LeetCoding-Challenge/23-Single-Number-III/Single-Number-III.kt @@ -0,0 +1,18 @@ +package string_integer + +class SingleNumberIIIKotlin260 { + fun singleNumber(nums: IntArray): IntArray { + var flag = nums.reduce { acc, i -> acc.xor(i) } + flag = flag.and(-flag) + var r1 = 0 + var r2 = 0 + nums.forEach { + if (it.and(flag) == 0) { + r1 = r1.xor(it) + } else { + r2 = r2.xor(it) + } + } + return intArrayOf(r1, r2) + } +} diff --git a/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt new file mode 100644 index 0000000..db96359 --- /dev/null +++ b/July-LeetCoding-Challenge/24-All-Paths-From-Source-to-Target/All-Paths-From-Source-to-Target.kt @@ -0,0 +1,44 @@ +package depth_first_search + +import java.util.* +import kotlin.collections.ArrayList + +class AllPathsFromSourcetoTargetKotlin797 { + fun allPathsSourceTarget(graph: Array): List> { + val result: MutableList> = LinkedList() + val subsets: MutableList = LinkedList() + + dfs(result, subsets, graph, 0) + return result + } + + private fun dfs( + result: MutableList>, + subsets: MutableList, + graph: Array, + index: Int + ) { + subsets.add(index) + if (graph[index].isEmpty()) { + result.add(ArrayList(subsets)) + } else { + graph[index].forEach { + dfs(result, subsets, graph, it) + subsets.removeAt(subsets.size - 1) + } + } + } +} + +fun main() { + val solution = AllPathsFromSourcetoTargetKotlin797() + val result = solution.allPathsSourceTarget( + arrayOf( + intArrayOf(1, 2), + intArrayOf(3), + intArrayOf(3), + intArrayOf() + ) + ) + println(result) +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt b/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt new file mode 100644 index 0000000..a174855 --- /dev/null +++ b/July-LeetCoding-Challenge/25-Find-Minimum-in-Rotated-Sorted-Array-II/Find-Minimum-in-Rotated-Sorted-Array-II.kt @@ -0,0 +1,24 @@ +package binary_search + +class FindMinimuminRotatedSortedArrayKotlin153 { + fun findMin(nums: IntArray): Int { + var left = 0 + var right = nums.size - 1 + while (left + 1 < right) { + val mid = left + (right - left) / 2 + when { + nums[mid] >= nums[0] -> { + if (nums[mid] < nums[nums.size - 1]) { + return nums[0] + } else { + left = mid + } + } + nums[mid] <= nums[nums.size - 1] -> { + right = mid + } + } + } + return minOf(nums[left], nums[right]) + } +} \ No newline at end of file diff --git a/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt b/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt new file mode 100644 index 0000000..50a5adb --- /dev/null +++ b/July-LeetCoding-Challenge/26-Add-Digits/Add-Digits.kt @@ -0,0 +1,31 @@ +package string_integer + +class AddDigitsKotlin258 { + fun addDigits(num: Int): Int = + if (num == 0) 0 else 1 + (num - 1) % 9 + + /* + fun addDigits(num: Int): Int { + return when { + num == 0 -> 0 + num % 9 == 0 -> 9 + else -> num % 9 + } + } + */ + /* + fun addDigits(num: Int): Int { + var result = 0 + var current = num + while (current != 0) { + result += current % 10 + current /= 10 + if (current == 0 && result > 9) { + current = result + result = 0 + } + } + return result + } + */ +} \ No newline at end of file