# 缺失的第一个正数

给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。

 

进阶:你可以实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案吗?

 

示例 1:

输入:nums = [1,2,0]
输出:
3

示例 2:

输入:nums = [3,4,-1,1]
输出:
2

示例 3:

输入:nums = [7,8,9,11,12]
输出:
1

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; vector nums = {1, 2, 0}; int res = 8; res = sol.firstMissingPositive(nums); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: int firstMissingPositive(vector &nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { while (nums[i] > 0 && nums[i] < n && nums[nums[i] - 1] != nums[i]) { swap(nums[i], nums[nums[i] - 1]); } } for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) break; } return n + 1; } }; ``` ## 选项 ### A ```cpp class Solution { public: int firstMissingPositive(vector &nums) { if (nums.size() == 0) { return 1; } int i = 0; while (i < nums.size()) { if (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.size() && nums[nums[i] - 1] != nums[i]) { swap(nums[i], nums[nums[i] - 1]); } else { i++; } } for (i = 0; i < nums.size(); i++) { if (nums[i] != i + 1) { break; } } return i + 1; } }; ``` ### B ```cpp class Solution { public: int firstMissingPositive(vector &nums) { int i, k, n = nums.size(); for (i = 0; i < n; i++) { while (nums[i] > 0 && nums[i] <= n) { k = nums[i] - 1; if (nums[k] == nums[i]) break; swap(nums[i], nums[k]); } } for (i = 0; i < n; i++) { if (i + 1 != nums[i]) break; } return i + 1; } }; ``` ### C ```cpp class Solution { public: int firstMissingPositive(vector &nums) { int n = nums.size(); for (int i = 0; i < n; i++) { if (nums[i] <= 0 || nums[i] > n || (nums[nums[i] - 1] == nums[i])) continue; swap(nums[nums[i] - 1], nums[i]); i--; } for (int i = 0; i < n; i++) { if (nums[i] != i + 1) return i + 1; } return n + 1; } }; ```