[Problem Name](probelm link/description)
Description:
Given an unsorted integer array, find the first missing positive integer.
Example
Example 1:
Input:[1,2,0]
Output:3
Example 2:
Input:[3,4,-1,1]
Output:2
Challenge
Your algorithm should run in O(n) time and uses constant space.
Main Idea:
Integer Array Problem. Iterate the array, if the element nums[i] = k greater than 0 AND less than the size of array, swap nums[i] & nums[k-1]. After adjustments, then check if nums[i] == i+1. If so, continue; If not, return i+1;
Tips/Notes:
- If every element is on it’s right place, then return the size of nums +1.
Time/Space Cost:
Time Cost: O ( n ) \ O(n) O(n)
Code:
class Solution {
public:
/**
* @param A: An array of integers
* @return: An integer
*/
int firstMissingPositive(vector<int> &A) {
// write your code here
int n = A.size();
vector<int> tmp(n, INT_MIN);
for(int i = 0; i < n; i++){
if(A[i] >0 && A[i] <= n){
tmp[A[i]-1] = A[i];
}
}
int res = n+1;
for(int i = 0; i < n; i++){
if(tmp[i] != i+1){
res = i+1;
return res;
}
}
return res;
}
};