forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjdalma.kt
More file actions
41 lines (34 loc) ยท 1.19 KB
/
jdalma.kt
File metadata and controls
41 lines (34 loc) ยท 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package leetcode_study
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
class `missing-number` {
fun missingNumber(nums: IntArray): Int {
return usingSum(nums)
}
/**
* 1. ๋ฐฐ์ด์ ์ถ๊ฐ๋ก ์์ฑํ์ฌ ์กด์ฌํ๋ ์ ์์ ์ธ๋ฑ์ค์ true๋ฅผ ์ ์ฅํ์ฌ, false์ธ ์ธ๋ฑ์ค๋ฅผ ๋ฐํํ๋ค.
* TC: O(n), SC: O(n)
*/
private fun usingIndex(nums: IntArray): Int {
val existed = BooleanArray(nums.size + 1)
nums.forEach { existed[it] = true }
existed.forEachIndexed { i, e ->
if (!e) return i
}
return -1
}
/**
* 2. 0๋ถํฐ ์ ์ ๋ฐฐ์ด์ ์ฌ์ด์ฆ๋งํผ ์ ์๋ฅผ ํฉ์ฐํ์ฌ ๊ธฐ๋ํ๋ ํฉ์ฐ๊ณผ ๋บ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค.
* TC: O(n), SC: O(1)
*/
private fun usingSum(nums: IntArray): Int {
val size = nums.size
return nums.fold((size + 1) * size / 2) { acc , i -> acc - i }
}
@Test
fun `์
๋ ฅ๋ฐ์ ์ ์ ๋ฐฐ์ด์์ ๋น์ด์๋ ์ ์๋ฅผ ๋ฐํํ๋ค`() {
missingNumber(intArrayOf(3,2,1)) shouldBe 0
missingNumber(intArrayOf(3,0,1)) shouldBe 2
missingNumber(intArrayOf(9,6,4,2,3,5,7,0,1)) shouldBe 8
}
}