Solution to Perm-Check by codility | Code Says
http://www.martinkysel.com/codility-permcheck-solution/
http://codility-lessons.blogspot.com/2014/04/lesson-2-permcheck_20.html
Traverse twice:
A non-empty zero-indexed array A consisting of N integers is given.
A permutation is a sequence containing each element from 1 to N once, and only once.
For example, array A such that:
A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2
is a permutation, but array A such that:
A[0] = 4 A[1] = 1 A[2] = 3
is not a permutation, because value 2 is missing.
The goal is to check whether array A is a permutation.
Write a function:
int solution(int A[], int N);
that, given a zero-indexed array A, returns 1 if array A is a permutation and 0 if it is not.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class Solution {
public static int solution(int[] A) {
int[] counter = new int [A.length];
for(int i= 0; i< A.length; i++){
if (A[i] < 1 || A[i] > A.length) {
// Out of range
return 0;
}
else if(counter[A[i]-1] == 1) {
// met before
return 0;
}
else {
// first time meet
counter[A[i]-1] = 1;
}
}
return 1;
}
}
|
def
solution(A):
seen
=
[
False
]
*
len
(A)
for
value
in
A:
if
0
<
=
value >
len
(A):
return
0
if
seen[value
-
1
]
=
=
True
:
return
0
seen[value
-
1
]
=
True
return
1
Traverse twice:
int solution(int A[], int N)
{
int B[N];
memset(B, 0x00, sizeof(B));
int i;
for (i = 0; i < N; i++){
if (A[i] > N){
return 0;
}
B[A[i] - 1] = 1;
}
for (i = 1; i < N; i++){
if (B[i] == 0){
return 0;
}
}
return 1;
}
Read full article from Solution to Perm-Check by codility | Code Says