Painless
PermCheck
Check if array A is a permutation.
Given a non-empty array A consisting of N integers.
A permutation is a sequence that contains each element from 1 to N only once.
For example, the following array A:
A [0] = 4
A [1] = 1
A [2] = 3
A [3] = 2
Is a permutation, but array A looks like this:
A [0] = 4
A [1] = 1
A [2] = 3
Is not a permutation because the value 2 is missing.
The goal is to see if array A is permuted.
Write a function:
class solution {public int solution(int [] A); }
That is, given array A, it returns 1 if array A is permuted, 0 otherwise.
For example, given the following array A:
A [0] = 4
A [1] = 1
A [2] = 3
A [3] = 2
The function must return 1.
Given the following array A:
A [0] = 4
A [1] = 1
A [2] = 3
The function must return 0.
Write an efficient algorithm for the following assumptions:
Program PermCheckSolution.java
PermCheckSolution.java
public int solution(int[] A) {
java.util.Arrays.sort(A);
for (int i = 0; i < A.length; i++) {
if (A[i] == i + 1) continue;
else return 0;
}
return 1;
}
Detected time complexity:
O(N) or O(N * log(N))
jUnit PermCheckSolutionTest.java
Report Candidate Report: trainingVGBR4Z-S47
Recommended Posts