티스토리 뷰
Codility - PermCheck 순열 체크하는 문제
A non-empty 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:
function solution(A);
that, given an array A, returns 1 if array A is a permutation and 0 if it is not.
For example, given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
A[3] = 2
the function should return 1.
Given array A such that:
A[0] = 4
A[1] = 1
A[2] = 3
the function should return 0.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [1..1,000,000,000].
Solution
function solution(A) {
const len = A.length;
if(len < 1 || len > 100000) {
return 0;
}
const aSum = len*(len+1) / 2; // 현재 A의 길이의 대한 총합
const distinctA = new Set(A); // 중복제거(순열이라면 1 ~ N 까지 한 번만 있을것)
const aRealSum = [...distinctA].reduce((acc, cur) => acc + cur); // 중복 제거후 각 요소에 대한 전체 합
return aSum === aRealSum ? 1 : 0;
}