Created
June 25, 2016 17:37
-
-
Save tiagopereira17/8848a1829783a9538c3c24e606ec4afb to your computer and use it in GitHub Desktop.
Check whether array A is a permutation.
This file contains 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 PermCheck { | |
public int checkIfIsPermutation(int[] A) { | |
if(A == null || A.length == 0) { | |
return -1; | |
} | |
int[] passed = new int[A.length]; | |
for(int i = 0; i < passed.length; i++) { | |
passed[i] = -1; | |
} | |
int missing = passed.length; | |
for(int i = 1; i <= A.length; i++) { | |
if(A[i - 1] < 1 || A[i - 1] > A.length) { | |
return 0; | |
} | |
if(passed[A[i - 1] - 1] != -1) { | |
return 0; | |
} else { | |
passed[A[i - 1] -1] = i; | |
missing -= 1; | |
} | |
} | |
if(missing == 0) { | |
return 1; | |
} | |
return 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment