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/
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/
'SW > 알고리즘 문제풀이' 카테고리의 다른 글
[Codility] Lesson5 - Prefix Sums: Genomic Range Query (0) | 2020.12.21 |
---|---|
[Codility] Lesson5 - Prefix Sums : Count Div (0) | 2020.12.21 |
[Codility] Lesson4 - Counting Elements : Perm Check (c++) (0) | 2020.12.20 |
[Codility] Lesson4 - Counting Elements: Frog River One (c++) (0) | 2020.12.19 |
[Codility] Lesson3 - Time Complexity: Tape Equilibrium (C++) (0) | 2020.12.19 |
댓글