
4-2. 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:
class Solution { public int solution(int[] 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].
즉 주어진 배열이 순열이면 1을 리턴 아니면 0을 리턴해주면 되는 문제입니다.
문제풀이
import java.util.*;
class Solution {
public int solution(int[] A) {
int N = A.length;
Arrays.sort(A);
for(int i = 0; i < N; i++){
if((i+1) != A[i]){
return 0;
}
}
return 1;
}
}
간단한 방식으로 받은 배열은 sort를 통해 정렬해주고
배열과 반복문의(i+1) <- [0부터 시작함으로 +1해줌] 을 통해 반복문 중 일치하지 않는다면 0을 리턴 전부 일치하면 반복문에서 빠져나온후 1을 리턴해줍니다.
실행결과

문제풀어보기 -> https://app.codility.com/programmers/lessons/4-counting_elements/perm_check/