File tree Expand file tree Collapse file tree 4 files changed +63
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal Expand file tree Collapse file tree 4 files changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // 시간 복잡도 : O(n^2)
3
+ fun threeSum (nums : IntArray ): List <List <Int >> {
4
+ val mutableSet = mutableSetOf<List <Int >>() // 결과를 담기 위한 set. 중복을 없애야되서 set으로 만듬.
5
+ nums.sort() // 1. nums array를 정렬해주고
6
+ for (i in 0 .. nums.size - 3 ) {
7
+ for (j in i + 1 .. nums.size - 2 ) {
8
+ for (k in j + 1 .. nums.lastIndex) {
9
+ // 2. nums의 3숫자를 뽑아내기 위해 i, j, k를 순차적으로 조회하면서 합했을때 0이 되는지 체크.
10
+ if (nums[i] + nums[j] + nums[k] == 0 ) {
11
+ mutableSet.add(listOf (nums[i], nums[j], nums[k]))
12
+ }
13
+ }
14
+ }
15
+ }
16
+ return mutableSet.toList() // 3. 최종적으로 뽑아낸 결과를 return값에 맞게 set > list로 변환.
17
+ }
18
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // 시간복잡도 : O(n)
3
+ fun climbStairs (n : Int ): Int {
4
+ val dp = IntArray (n+ 1 )
5
+ dp[1 ] = 1
6
+ dp[2 ] = 2
7
+ for (i in 3 .. n){ // 3부터 n까지 for문.
8
+ dp[i] = dp[i- 1 ] + dp[i- 2 ]
9
+ }
10
+ return dp[n]
11
+ }
12
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // 시간 : O(n^2)
3
+ fun buildTree (preorder : IntArray , inorder : IntArray ): TreeNode ? {
4
+ if (preorder.isEmpty() || inorder.isEmpty()) {
5
+ return null
6
+ }
7
+ val value = preorder[0 ]
8
+ var mid = inorder.indexOf(value)
9
+ if (mid < 0 ) {
10
+ mid = 0
11
+ }
12
+ val leftNode = buildTree(
13
+ preorder.slice(1 .. preorder.lastIndex).toIntArray(),
14
+ inorder.slice(0 until mid).toIntArray())
15
+ val rightNode = buildTree(
16
+ preorder.slice(2 .. preorder.lastIndex).toIntArray(),
17
+ inorder.slice(mid + 1 .. inorder.lastIndex).toIntArray()
18
+ )
19
+
20
+ return TreeNode (value).apply {
21
+ left = leftNode
22
+ right = rightNode
23
+ }
24
+ }
25
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ // 시간 복잡도 : O(nlog(n))
3
+ fun isAnagram (s : String , t : String ): Boolean {
4
+ val sortS = s.toCharArray().apply { sort() } // string을 char array로 변환 후 정렬.
5
+ val sortT = t.toCharArray().apply { sort() }
6
+ return sortS.concatToString() == sortT.concatToString() // 정렬된 char array를 string으로 만든후 비교.
7
+ }
8
+ }
You can’t perform that action at this time.
0 commit comments