Skip to content

Instantly share code, notes, and snippets.

@pdu
Created January 7, 2013 14:18
Show Gist options
  • Select an option

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

Select an option

Save pdu/4475290 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
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i = 0; i < n; ++i)
while (A[i] >= 1 && A[i] <= n && A[i] != i + 1 && A[i] != A[A[i] - 1])
swap(A[i], A[A[i] - 1]);
int ret;
for (ret = 1; ret <= n; ++ret)
if (A[ret - 1] != ret)
break;
return ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment