Task description
A zero-indexed 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.
라는 문제다. 간단하게, 주어진 배열에서 사라진 숫자를 찾는거다. 해당 배열은 N개의 서로 다른 정수가 존재하며, N의 범위는 1부터 N+1만큼이다.
먼저 떠오른 생각은, 현재 배열에 존재하는 모든 원소들의 합산한 값과 (실제로는 어떤수가 빠진 나머지들의 합) 빠진수를 포함한 합을 구해 뺄셈을 하면, 찾고자 하는 수가 나온다는 것.
이대로 구현을 하면 아래와 같다.
1 2 3 4 5 6 7 8 9 | int solution(vector<int> &A){ unsigned int numRange = A.size() + 1; unsigned int sum = (numRange * (1+numRange))/2; unsigned int missingSum = 0; for(unsigned int idx = 0; idx < A.size(); idx++) missingSum += A[idx]; return sum - missingSum; } |
p.s. 뭔가 참신한 방법이 없을까? 해당 레슨 문제의 코멘터리쪽을 살펴봐야 하겠다.
댓글 없음:
댓글 쓰기