Created
April 20, 2016 16:04
-
-
Save cruxrebels/042bb25c65ecb16f138aee056c4e1e2d to your computer and use it in GitHub Desktop.
Given an unsorted integer array, find the first missing positive integer. Example: Given [1,2,0] return 3, [3,4,-1,1] return 2, [-8, -7, -6] returns 1 Your algorithm should run in O(n) time and use constant space. Tags: InterviewBit Array Problem https://www.interviewbit.com/problems/first-missing-integer/
This file contains hidden or 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
int Solution::firstMissingPositive(vector<int> &A) { | |
sort(A.begin(), A.end()); | |
int c = 1; | |
for (auto const& a : A) | |
{ | |
if (a<1) | |
continue; | |
else if (a==c) | |
{ | |
++c; | |
continue; | |
} | |
else | |
break; | |
} | |
return c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solution must be O(n) and your solution in O(nlogn)