File tree Expand file tree Collapse file tree 3 files changed +95
-0
lines changed
best-time-to-buy-and-sell-stock
encode-and-decode-strings Expand file tree Collapse file tree 3 files changed +95
-0
lines changed Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /*
4
+ * 두 거래일 사이 최고의 수익을 구하는 문제
5
+ * 시간 복잡도: O(n^2)
6
+ * -> 모든 경우의 수를 순회하며 거래일 사이 최고 가격을 구하는 로직: O(n^2)
7
+ * 공간 복잡도: O(1)
8
+ * 아래 로직은 시간 초과 발생 O(n^2)의 복잡도를 줄여야함.
9
+ * */
10
+ fun maxProfit (prices : IntArray ): Int {
11
+ var result = Int .MIN_VALUE
12
+
13
+ for (i in prices.indices) {
14
+ for (j in i + 1 until prices.size) {
15
+ if (prices[i] < prices[j]) {
16
+ if (result < prices[j] - prices[i]) {
17
+ result = prices[j] - prices[i]
18
+ }
19
+ }
20
+ }
21
+ }
22
+ if (result == Int .MIN_VALUE ) return 0
23
+ return result
24
+ }
25
+
26
+ /*
27
+ * 가장 작은 값을 저장하는 변수와 가장 큰 수익을 갖는 변수를 두고 문제 해결
28
+ * 시간 복잡도: O(n)
29
+ * 공간 복잡도: O(1)
30
+ * */
31
+ fun maxProfit2 (prices : IntArray ): Int {
32
+ var minValue = Int .MAX_VALUE
33
+ var maxValue = 0
34
+
35
+ for (price in prices) {
36
+ if (price < minValue) {
37
+ minValue = price
38
+ } else if (price - minValue > maxValue) {
39
+ maxValue = price - minValue
40
+ }
41
+ }
42
+ return maxValue
43
+ }
Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /*
4
+ * 문자열 인코딩 디코딩 문제
5
+ * 시간 복잡도: O(n)
6
+ * 공간 복잡도: O(n)
7
+ * */
8
+ fun encoding (strs : List <String >): String {
9
+ var result = " "
10
+ if (strs.isEmpty()) return result
11
+ for (index in 0 until strs.size - 1 ) {
12
+ if (strs[index] == " :" ) {
13
+ result + = strs[index] + " ::;"
14
+ } else {
15
+ result + = strs[index] + " :;"
16
+ }
17
+ }
18
+ result + = strs[strs.size - 1 ]
19
+ return result
20
+ }
21
+
22
+ fun decoding (str : String ): List <String >{
23
+ val splitedStrList = str.split(" :;" )
24
+ val result = mutableListOf<String >()
25
+ for (splitStr in splitedStrList){
26
+ if (splitStr == " ::" ) {
27
+ result.add(" :" )
28
+ } else {
29
+ result.add(splitStr)
30
+ }
31
+ }
32
+ return result
33
+ }
Original file line number Diff line number Diff line change
1
+ package leetcode_study
2
+
3
+ /*
4
+ * 주어진 문자열 배열에서 anagram을 그룹핑하는 문제
5
+ * 자료구조 Map을 사용해 문제 해결. 오름차순으로 정렬한 char type을 재조합해 key 값으로 사용. value는 조회 대상 문자열
6
+ * 시간 복잡도: O(n)
7
+ * 공간 복잡도: O(n)
8
+ * */
9
+ fun groupAnagrams (strs : Array <String >): List <List <String >> {
10
+ val result = mutableMapOf<String , MutableList <String >>()
11
+
12
+ for (str in strs) {
13
+ val key = str.toCharArray().sorted().joinToString(" " )
14
+ result.computeIfAbsent(key) { mutableListOf () }.add(str)
15
+ }
16
+
17
+ if (strs.isEmpty()) return listOf (listOf ())
18
+ return result.values.toList()
19
+ }
You can’t perform that action at this time.
0 commit comments