File tree Expand file tree Collapse file tree 3 files changed +81
-0
lines changed
best-time-to-buy-and-sell-stock
implement-trie-prefix-tree Expand file tree Collapse file tree 3 files changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * 시간 복잡도: O(n)
3
+ * 공간 복잡도: O(1)
4
+ */
5
+
6
+ class Solution {
7
+ fun maxProfit (prices : IntArray ): Int {
8
+ var minPrice = Int .MAX_VALUE
9
+ var maxProfit = 0
10
+
11
+ prices.forEach { price ->
12
+ minPrice = minOf(minPrice, price)
13
+ maxProfit = maxOf(maxProfit, price - minPrice)
14
+ }
15
+
16
+ return maxProfit
17
+ }
18
+ }
Original file line number Diff line number Diff line change
1
+ /* *
2
+ * N: 단어 개수, M: 평균 단어 길이
3
+ * 시간 복잡도: O(N × M log M)
4
+ * 공간 복잡도: O(N × M)
5
+ */
6
+
7
+ class Solution {
8
+ fun groupAnagrams (strs : Array <String >): List <List <String >> {
9
+ val groupMap = mutableMapOf<String , MutableList <String >>()
10
+
11
+ for (str in strs) {
12
+ val sortedKey = str.toCharArray().sorted().joinToString(" " )
13
+ groupMap.getOrPut(sortedKey) { mutableListOf ()}.add(str)
14
+ }
15
+
16
+ return groupMap.values.toList()
17
+ }
18
+ }
Original file line number Diff line number Diff line change
1
+ /* *
2
+ * 시간복잡도: O(L) (insert, search, startsWith 모두 동일)
3
+ * 공간복잡도: O(ΣL × alphabetSize)
4
+ */
5
+
6
+ class Trie () {
7
+
8
+ private class Node {
9
+ val child = arrayOfNulls<Node >(26 )
10
+ var isEnd: Boolean = false
11
+ }
12
+
13
+ private val root = Node ()
14
+
15
+ fun insert (word : String ) {
16
+ var cur = root
17
+ for (ch in word) {
18
+ val i = ch - ' a'
19
+ if (cur.child[i] == null ) {
20
+ cur.child[i] = Node ()
21
+ }
22
+ cur = cur.child[i]!!
23
+ }
24
+ cur.isEnd = true
25
+ }
26
+
27
+ fun search (word : String ): Boolean {
28
+ val node = findNode(word)
29
+ return node?.isEnd == true
30
+ }
31
+
32
+ fun startsWith (prefix : String ): Boolean {
33
+ return findNode(prefix) != null
34
+ }
35
+
36
+ private fun findNode (s : String ): Node ? {
37
+ var cur = root
38
+ for (ch in s) {
39
+ val i = ch - ' a'
40
+ val next = cur.child[i] ? : return null
41
+ cur = next
42
+ }
43
+ return cur
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments