Created
February 19, 2013 12:58
-
-
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
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
| 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