Skip to content

Commit 20bf430

Browse files
committed
Create 0041-first-missing-positive.kt
1 parent 26e64ae commit 20bf430

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Diff for: kotlin/0041-first-missing-positive.kt

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
fun firstMissingPositive(nums: IntArray): Int {
3+
var i = 0
4+
// if we encounter a valid integer, swap it into its right place. Ignore all numbers larger than nums.length
5+
while(i < nums.size) {
6+
val pos = nums[i] - 1
7+
if(pos in (0 until nums.size) && nums[i] != nums[pos]) nums.swap(i, pos)
8+
else i++
9+
}
10+
11+
//if the expected number is not in its right place, return it
12+
for(i in nums.indices){
13+
if (nums[i] != i + 1) return i + 1
14+
}
15+
return nums.size + 1
16+
}
17+
private fun IntArray.swap(i: Int, j: Int) {
18+
this[i] = this[j].also{ this[j] = this[i]}
19+
}
20+
}

0 commit comments

Comments
 (0)