Work/Algorithm

코딜리티 레슨4 Counting Elements 4 - PermCheck

다랑 2020. 12. 3. 11:20
728x90

문제

 

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].

Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

→ 배열이 순열이면 1, 순열이 아니면 0을 리턴한다.

 

답변

 

1. 배열을 순열로 만들고~

2. 중간에 빈 값이 있는지 체크합니다.

3. 빈 값을 체크하는 방법은... for문의 index를 빗겨나는 값이 있으면 일단 check

 

// you can also use imports, for example:
// import java.util.*;
import java.util.Arrays;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        int rslt = 1, compare = 1, fin = 0;
        
        Arrays.sort(A);
        
        for(int a : A) {
            if(a != compare) fin = compare;
            compare++;
        }
        
        if(fin != 0) rslt = 0;
        
        return rslt;
    }
}

 

결과

 

https://app.codility.com/demo/results/trainingCU8XHN-T6G/

728x90