Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 19, 2013 12:58
Show Gist options
  • Select an option

  • Save pdu/4985648 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4985648 to your computer and use it in GitHub Desktop.
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. http://leetcode.com/onlinejudge#question_41
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i = 0; i < n; ++i) {
int id = i;
while (A[id] != id + 1 && A[id] >= 1 && A[id] <= n && A[id] != A[A[id] - 1])
swap(A[id], A[A[id] - 1]);
}
for (int i = 0; i < n; ++i)
if (A[i] != i + 1)
return i + 1;
return n + 1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment