Created
May 15, 2014 13:38
-
-
Save Cee/df79829d1ce5da3c1aa9 to your computer and use it in GitHub Desktop.
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
public class Solution { | |
public int firstMissingPositive(int[] A) { | |
if (A.length == 0) return 1; | |
for (int i = 0; i < A.length; i++) { | |
if (A[i] <= A.length && A[i] > 0 && A[i] != i+1) { | |
if (A[A[i]-1] != A[i]) { | |
int tmp = A[A[i]-1]; | |
A[A[i]-1] = A[i]; | |
A[i] = tmp; | |
i--; | |
} | |
} | |
} | |
for (int i = 0; i < A.length; i++) { | |
if (A[i] != i+1) return i+1; | |
} | |
return A.length+1; | |
} | |
} |
自己的想法:
一个HashMap维护(但是要额外的空间)
尽管是O(n)的但是空间也是....
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
很巧妙的一个答案。
比自己的想法好很多然后就贴过来了。