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:
(Copyright 2009–2023 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.)
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;
}
}
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;
}
}
배열의 범위는 [1 ~ (N+1)] 까지 이므로 마지막 요소 빠진 경우도 고려해야 함
예를 들어, [1] 의 경우에는 N = 1 이므로 [1, 2] 가 되는 것이 맞음
따라서, 빠진 숫자는 항상 존재하고, for문에서 검출되지 않는 빠진 숫자는 항상 마지막 요소이므로 마지막 요소를 return 해야 함