We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 26e64ae commit 20bf430Copy full SHA for 20bf430
kotlin/0041-first-missing-positive.kt
@@ -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