코딩테스트##009 PermMissingElem

A Kind Dev·2023년 2월 1일
0

코딩테스트

목록 보기
9/19

문제

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

(Copyright 2009–2023 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.)


나의 풀이

풀이 1 --> 50% (정확도)

import java.util.*;

class Solution {
    public int solution(int[] A) {
        
        Arrays.sort(A);

        int num = 0;
        for (int i = 0; i < A.length; i++) {
            if (i + 1 != A[i]) {
                num = i + 1;
                break;
            }
        }

        return num;
    }
}

풀이 2 --> 100%

import java.util.*;

class Solution {
    public int solution(int[] A) {
        
        Arrays.sort(A);

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

        return A.length + 1;
    }
}

check 1 : 문제를 꼼꼼히 읽자!

배열의 범위는 [1 ~ (N+1)] 까지 이므로 마지막 요소 빠진 경우도 고려해야 함
예를 들어, [1] 의 경우에는 N = 1 이므로 [1, 2] 가 되는 것이 맞음
따라서, 빠진 숫자는 항상 존재하고, for문에서 검출되지 않는 빠진 숫자는 항상 마지막 요소이므로 마지막 요소를 return 해야 함

profile
친절한 개발자

0개의 댓글