본문 바로가기

알고리즘

PermMissingElem_codility

문제

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.

 

Assume that:

  • 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)].

 

풀이

function(A) {
	A.sort((a, b) => a-b);
	for (let i = 0; i < A.length; i++) {
		if (i+1 != A[i]) {
			return i+1;
		}	
	}
	return A.length+1;
}

 

배열을 오름차순으로 변경한다.

배열의 갯수만큼 반복문을 돌다가 해당 index+1과 배열의 값이 일치하지 않을 때 값을 리턴시킨다.

배열의 첫번째 숫자나 마지막 숫자가 빠지는 경우를 고려하여 A.length+1 로직을 마지막에 작성했다.

 

'알고리즘' 카테고리의 다른 글

Prefix Sums_Codility  (0) 2022.04.04
TapeEquilibrium_codility  (0) 2022.03.11
FrogJmp_codility  (0) 2022.02.18
OddOccurrencesInArray_Codility  (0) 2022.02.16
CyclicRotation_Codility  (0) 2022.02.15