본문으로 바로가기

Description

주어진 배열에서 1~N+1 사이의 값중 비어있는 값을 찾아서 반환하는 문제입니다.

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:

class Solution { public int solution(int[] 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)].

Solution 1. 정렬(Sort)

public int solution(int[] A) {

    int len = A.length;
    Arrays.sort(A);
    for(int i = 0; i < len; i++){
        if(A[i] != i+1){
            return i+1;
        }
    }
    return len+1;
}

정렬 후 반복을 통해 없는 숫자(index+1)이 아닌 경우 해당 값을 반환합니다. 맨마지막 번호가 없는 edge케이스를 위해 반복 후 에는 마지막 번호를 반환해줍니다.

Reference

 

PermMissingElem coding task - Learn to Code - Codility

Find the missing element in a given permutation.

app.codility.com