41. First Missing Positive Hard
1/**
2 * [41] First Missing Positive
3 *
4 * Given an unsorted integer array nums, return the smallest missing positive integer.
5 * You must implement an algorithm that runs in O(n) time and uses constant extra space.
6 *
7 * Example 1:
8 * Input: nums = [1,2,0]
9 * Output: 3
10 * Example 2:
11 * Input: nums = [3,4,-1,1]
12 * Output: 2
13 * Example 3:
14 * Input: nums = [7,8,9,11,12]
15 * Output: 1
16 *
17 * Constraints:
18 *
19 * 1 <= nums.length <= 5 * 10^5
20 * -2^31 <= nums[i] <= 2^31 - 1
21 *
22 */
23pub struct Solution {}
24
25// problem: https://leetcode.com/problems/first-missing-positive/
26// discuss: https://leetcode.com/problems/first-missing-positive/discuss/?currentPage=1&orderBy=most_votes&query=
27
28// submission codes start here
29
30impl Solution {
31 pub fn first_missing_positive(x: Vec<i32>) -> i32 {
32 // immutable x as input
33 let mut nums = x.clone();
34 let mut i = 0;
35 while i < nums.len() {
36 if nums[i] <= 0 || nums[i] == i as i32 + 1 || nums[i] >= nums.len() as i32 {
37 i += 1;
38 continue;
39 } else if nums[nums[i] as usize - 1] != nums[i] {
40 let y = nums[i];
41 nums.swap(i, y as usize - 1);
42 } else {
43 i += 1;
44 }
45 }
46 let mut result = 0;
47 while result < nums.len() && nums[result] == result as i32 + 1 {
48 result += 1;
49 }
50 result as i32 + 1
51 }
52}
53
54// submission codes end
55
56#[cfg(test)]
57mod tests {
58 use super::*;
59
60 #[test]
61 fn test_41() {
62 assert_eq!(
63 Solution::first_missing_positive(vec![-1, 4, 2, 1, 9, 10]),
64 3
65 );
66 assert_eq!(Solution::first_missing_positive(vec![3, 4, -1, 1]), 2);
67 assert_eq!(Solution::first_missing_positive(vec![1, 2, 0]), 3);
68 assert_eq!(Solution::first_missing_positive(vec![2, 1]), 3);
69 }
70}
71
Back
© 2025 bowen.ge All Rights Reserved.