Skip to content

Commit ce094af

Browse files
committed
solved: 41. First Missing Positive
Signed-off-by: rajput-hemant <rajput.hemant2001@gmail.com>
1 parent 6ef5840 commit ce094af

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
impl Solution {
2+
pub fn first_missing_positive(nums: Vec<i32>) -> i32 {
3+
let (mut nums, mut i) = (nums, 0);
4+
5+
while i < nums.len() {
6+
let num = nums[i];
7+
8+
// if the number is in the range [1, nums.len()] and not in the right position
9+
// swap it with the number at the right position
10+
if num > 0 && num <= nums.len() as i32 && num != nums[num as usize - 1] {
11+
nums.swap(i, num as usize - 1);
12+
} else {
13+
i += 1;
14+
}
15+
}
16+
17+
// find the first missing positive number
18+
for (i, num) in nums.iter().enumerate() {
19+
if num != &(i as i32 + 1) {
20+
return i as i32 + 1;
21+
}
22+
}
23+
24+
nums.len() as i32 + 1
25+
}
26+
}

0 commit comments

Comments
 (0)