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

[Codility] Lesson4 - Counting Elements : Missing Integer (c++)

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

Problem

This is a demo task.

Write a function:

int solution(vector<int> &A);

that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

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,000,000..1,000,000].

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

 

app.codility.com/programmers/lessons/4-counting_elements/missing_integer/

 

MissingInteger coding task - Learn to Code - Codility

Find the smallest positive integer that does not occur in a given sequence.

app.codility.com

How to solve

- 구해야 하는것?

배열 A에 없는 가장 작은 양의 정수 

 

- 풀이

minVal : missing value의 초기 값 설정한다.

벡터 A를 sorting 한다.

벡터를 1씩 증가키면서 A[i] == minVal 일 때, minVal +1 증가시킨다.

최종 minVal return

Solution(c++)

// you can use includes, for example:
#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();
    int minVal = 1;

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

    //
    for(int i=0; i<len; i++){
        if(A[i] == minVal){
            minVal++;
        }
    }
    return minVal;
}

Test Result

app.codility.com/demo/results/trainingSX6FW9-DP2/

 

Test results - Codility

This is a demo task. Write a function: int solution(vector &A); that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

app.codility.com

 

728x90

댓글