생산성/코딩테스트
코딩테스트[codility : javascript]
슬래기
2022. 3. 9. 15:26
This is a demo task.
Write a function:
function solution(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].
[번역]
이것은 데모 작업입니다.
함수 작성:
기능 솔루션(A);
N 정수의 배열 A가 주어지면 A에서 발생하지 않는 가장 작은 양의 정수(0보다 큼)를 반환합니다.
예를 들어 A = [1, 3, 6, 4, 1, 2]일 때 함수는 5를 반환해야 합니다.
A = [1, 2, 3]이 주어지면 함수는 4를 반환해야 합니다.
A = [−1, −3]이 주어지면 함수는 1을 반환해야 합니다.
다음 가정에 대한 효율적인 알고리즘을 작성하십시오.
N은 [1..100,000] 범위 내의 정수입니다.
배열 A의 각 요소는 [−1,000,000..1,000,000] 범위의 정수입니다.
코딜리티의 Easy문제이다.
[문제 해석]
배열이 주어졌을 때 양수의 값을 오름차순으로 정렬해서 주어진 배열에서 빠진값이 있으면 그 값을 return하고
오름차순이 전부 값이 있다면 가장 높은 값의 +1을 해주면 된다.
function solution(A) {
let result;
let answer;
let test;
// 중복 제거 및 0보다 큰 수 제거.
result = [...new Set(A.filter(e=>e>0))];
if(result.length==0) return 1;
// 오름차순 정렬
result = result.sort((a,b)=>(a-b));
// 오름차순 숫자만큼 배열 만들어 주기.
test = Array.apply(null,new Array(result.length)).map((e,i)=>i+1);
// 만들어준 배열과 중복제거한 배열을 비교
for(let [idx,value] of result.entries()){
if(value != test[idx]){
answer = test[idx];
break;
}
}
//빠진 값이 있다면 answer을 return 없다면 배열의 최대값에 +1
return answer ? answer : Math.max.apply(null,test) + 1;
// write your code in JavaScript (Node.js 8.9.4)
}