Created
June 19, 2019 22:09
-
-
Save adamkorg/8966ddf341efca934ee839da2d0353a6 to your computer and use it in GitHub Desktop.
Leetcode 41: First Missing Positive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <climits> | |
using namespace std; | |
int firstMissingPositive(vector<int>& nums) { | |
//first pass. replace all vals>n and <=0 with INT_MAX | |
int n = nums.size(); | |
for (int i=0; i<n; i++) { | |
if (nums[i] > n || nums[i] <= 0) | |
nums[i] = INT_MAX; | |
} | |
//add extra value, as we need it for elem indexes 1 -> n. | |
nums.push_back(INT_MAX); | |
//next pass to flag values we have by setting negatives in indexes of those values | |
for (int i=0; i<n; i++) { | |
if (abs(nums[i]) == INT_MAX) | |
continue; | |
if (nums[abs(nums[i])] > 0) | |
nums[abs(nums[i])] *= -1; | |
} | |
//final pass to find where we have not flagged a value (by -ve) and that index indicates the first missing positive. | |
int i=1; | |
for ( ; i<=n; i++) { | |
if (nums[i] > 0) | |
break; | |
} | |
return i; | |
} | |
int main() { | |
vector<int> nums {1,2,4,8,5,-3}; | |
int res = firstMissingPositive(nums); | |
cout << res << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment