Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0]
return 3
,
and [3,4,-1,1]
return 2
.
Your algorithm should run in O(n) time and uses constant space.
The simple idea is to use array's index to sort, placing the number to the correspond index slot.
My mistake solution is made because I think there is no duplicates. So, I made: nums[i] != (i + 1);
for i from 0 to size
if nums[i] != nums[nums[i] - 1] --> need swap.
I first made a mistake:
#include <vector> #include <iostream> using namespace std; // This code can't pass the following test case [1, 1] int firstMissingPositive(vector<int>& nums) { if(nums.size() == 0) return 0; int i = 0; while(i < nums.size()) { if(nums[i] > 0 && nums[i] <= nums.size() && nums[i] != (i + 1)) // here i + 1 is wrong! This will end into infinite loop swap(nums[nums[i] - 1], nums[i]); else i++; } for(i = 0; i < nums.size(); ++i) { if(nums[i] != (i + 1)) return i + 1; } return i + 1; } int main(void) { vector<int> nums{1, 1}; int missing = firstMissingPositive(nums); cout << missing << endl; }
#include <vector> #include <iostream> using namespace std; int firstMissingPositive(vector<int>& nums) { if(nums.size() == 0) return 0; int i = 0; while(i < nums.size()) { if(nums[i] > 0 && nums[i] <= nums.size() && nums[i] != nums[nums[i] - 1]) swap(nums[nums[i] - 1], nums[i]); else i++; } for(i = 0; i < nums.size(); ++i) { if(nums[i] != (i + 1)) return i + 1; } return i + 1; } int main(void) { vector<int> nums{1, 1}; int missing = firstMissingPositive(nums); cout << missing << endl; }