diff --git a/best-time-to-buy-and-sell-stock/hyunjung-choi.kt b/best-time-to-buy-and-sell-stock/hyunjung-choi.kt new file mode 100644 index 000000000..7c3f507e9 --- /dev/null +++ b/best-time-to-buy-and-sell-stock/hyunjung-choi.kt @@ -0,0 +1,18 @@ +/** + * 시간 복잡도: O(n) + * 공간 복잡도: O(1) + */ + +class Solution { + fun maxProfit(prices: IntArray): Int { + var minPrice = Int.MAX_VALUE + var maxProfit = 0 + + prices.forEach { price -> + minPrice = minOf(minPrice, price) + maxProfit = maxOf(maxProfit, price - minPrice) + } + + return maxProfit + } +} diff --git a/group-anagrams/hyunjung-choi.kt b/group-anagrams/hyunjung-choi.kt new file mode 100644 index 000000000..126ab2605 --- /dev/null +++ b/group-anagrams/hyunjung-choi.kt @@ -0,0 +1,18 @@ +/** + * N: 단어 개수, M: 평균 단어 길이 + * 시간 복잡도: O(N × M log M) + * 공간 복잡도: O(N × M) + */ + +class Solution { + fun groupAnagrams(strs: Array): List> { + val groupMap = mutableMapOf>() + + for (str in strs) { + val sortedKey = str.toCharArray().sorted().joinToString("") + groupMap.getOrPut(sortedKey) { mutableListOf()}.add(str) + } + + return groupMap.values.toList() + } +} diff --git a/implement-trie-prefix-tree/hyunjung-choi.kt b/implement-trie-prefix-tree/hyunjung-choi.kt new file mode 100644 index 000000000..16b8cb4db --- /dev/null +++ b/implement-trie-prefix-tree/hyunjung-choi.kt @@ -0,0 +1,45 @@ +/** + * 시간복잡도: O(L) (insert, search, startsWith 모두 동일) + * 공간복잡도: O(ΣL × alphabetSize) + */ + +class Trie() { + + private class Node { + val child = arrayOfNulls(26) + var isEnd: Boolean = false + } + + private val root = Node() + + fun insert(word: String) { + var cur = root + for (ch in word) { + val i = ch - 'a' + if (cur.child[i] == null) { + cur.child[i] = Node() + } + cur = cur.child[i]!! + } + cur.isEnd = true + } + + fun search(word: String): Boolean { + val node = findNode(word) + return node?.isEnd == true + } + + fun startsWith(prefix: String): Boolean { + return findNode(prefix) != null + } + + private fun findNode(s: String): Node? { + var cur = root + for (ch in s) { + val i = ch - 'a' + val next = cur.child[i] ?: return null + cur = next + } + return cur + } +}