[Codility] PermMissingElem (JavaScript)

Sohyeon Bak·2021년 11월 26일
0

Codility

목록 보기
3/19
post-thumbnail

문제

An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

Your goal is to find that missing element.

Write a function:

function solution(A);

that, given an array A, returns the value of the missing element.

For example, given array A such that:

A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5
the function should return 4, as it is the missing element.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].

문제해석

배열에는 1부터 1+n까지의 숫자가 들어가 있고, 1부터 순차적인 1+n까지 순차적으로 숫자가 들어있지만 순서는 뒤죽박죽으로 들어가 있다.
문제는 순차적인 숫자가 들어있는 배열에서 빠진 숫자를 찾는 것이다.

문제풀이

처음에 숫자를 비교하는 방식으로 풀었으나 제외적인 상황처리가 조금 난잡하게 되는 경향이 있어서 reduce를 사용해 전체 값을 더해 원래 순차적인 수를 더한 값에서 뺀 수를 답으로 지정했다.

  • A의 배열의 길이가 0이라면 답은 1
  • 그렇지 않다면 1+A.length까지 모두 더한 값에서 A의 모든 값을 더한 값을 뺀 것을 정답 처리

코드

function solution(A) {
    let answer = 0;
    let leng = A.length;

    if(leng===0){
        return answer+=1
    }else{
        let addTmp = ((leng+1) * (leng+2)) / 2;
        let add = A.reduce((a,b)=>a+b);

        return addTmp - add
    }
    
}

최종결과

시간복잡도는 O(N) or O(N * log(N))로 나왔다.

출처

https://app.codility.com/programmers/lessons/3-time_complexity/

profile
정리하고 기억하는 곳

0개의 댓글