본문 바로가기
SW/알고리즘 문제풀이

[Codility] Lesson4 - Counting Elements : Perm Check (c++)

by 미래미래로 2020. 12. 20.
728x90

Problem

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:

int solution(vector<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].

How to solve

- 정보

N개로 이루어진 배열 A

Permutation: 1~N까지 연속되는 수의 sequence

 

- 구해야 하는것?

Permutation array 유무를 체크하여, 

permutation array이면 return 1, 아니면 return 0

 

- 풀이

A 배열을 sorting 하고, 

A[i] != i+1 이 아닌 경우가 있으면, return 0

A[i] == i+1 케이스를 다 통과하면, return 1

Solution(c++)

#include <bits/stdc++.h>

// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;

int solution(vector<int> &A) {
    // write your code in C++14 (g++ 6.2.0)
    int len = A.size();

    // sort
    sort(A.begin(), A.end());

    for(int i=0; i<len; i++){
        if(A[i] == i+1){
            continue;
        }else{
            return 0;
        }
    }

    return 1;
    
}

Test Result

app.codility.com/demo/results/trainingPCZ7M3-AXM/

 

Test results - Codility

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

app.codility.com

 

728x90

댓글