Skip to content

Commit

Permalink
2문제 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
jdalma committed Oct 24, 2024
1 parent 9783cbe commit cfbe1ce
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 0 deletions.
61 changes: 61 additions & 0 deletions graph-valid-tree/jdalma.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package leetcode_study

import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test

class `graph-valid-tree` {

/**
* TC: O(n), SC: O(n)
*/
fun validTree(nodeSize: Int, edges: Array<IntArray>): Boolean {
if (nodeSize - 1 != edges.size) {
return false
}

val visited = mutableSetOf<Int>()
val adj = List(nodeSize) { mutableListOf<Int>() }
for (e in edges) {
adj[e[0]].add(e[1])
adj[e[1]].add(e[0])
}

val queue = ArrayDeque<Int>().apply {
this.add(0)
}

while (queue.isNotEmpty()) {
val now = queue.removeFirst()
visited.add(now)
for (next in adj[now]) {
if (!visited.contains(next)) {
queue.add(next)
}
}
}

return nodeSize == visited.size
}

@Test
fun `노드가 트리의 조건을 만족하는지 여부를 반환한다`() {
validTree(5,
arrayOf(
intArrayOf(0,1),
intArrayOf(0,2),
intArrayOf(0,3),
intArrayOf(1,4)
)
) shouldBe true

validTree(5,
arrayOf(
intArrayOf(0,1),
intArrayOf(0,2),
intArrayOf(0,3),
intArrayOf(1,4),
intArrayOf(2,3),
)
) shouldBe false
}
}
59 changes: 59 additions & 0 deletions insert-interval/jdalma.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package leetcode_study

import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import kotlin.math.max
import kotlin.math.min

class `insert-interval` {

/**
* TC: O(n), SC: O(n)
*/
fun insert(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
if (intervals.isEmpty()) return arrayOf(newInterval)
return justIterate(intervals, newInterval)
}

private fun justIterate(intervals: Array<IntArray>, newInterval: IntArray): Array<IntArray> {
val result = mutableListOf<IntArray>()
var new: IntArray? = newInterval

for (interval in intervals) {
if (new != null) {
if (new[1] < interval[0]) {
// new 범위가 더 앞에 있다
result.add(new)
result.add(interval)
new = null
} else if (new[0] > interval[1]) {
// new 범위가 더 뒤에 있어 다른 범위에 포함될 가능성이 있음
result.add(interval)
} else {
new[0] = min(new[0], interval[0])
new[1] = max(new[1], interval[1])
}
} else {
result.add(interval)
}
}
if (new != null) {
result.add(new)
}
return result.toTypedArray()
}

@Test
fun name() {
insert(
arrayOf(
intArrayOf(1,2),
intArrayOf(3,5),
intArrayOf(6,7),
intArrayOf(8,10),
intArrayOf(12,16)
),
intArrayOf(4,8)
) shouldBe arrayOf(intArrayOf(1,2), intArrayOf(3,10), intArrayOf(12,16))
}
}

0 comments on commit cfbe1ce

Please sign in to comment.