Created
January 7, 2013 14:18
-
-
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
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) | |
| 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