問題
The list holds n distinct numbers taken from 0, 1, …, n, so exactly one number in that range is missing. Find it. (Hint: compare the expected total with the actual total.)
Implement missing_number(numbers).
Input
numbers: n distinct numbers from 0 to n.
Output
Return the missing number.
制約
0 ≤ n ≤ 100,000
例
入力:
numbers = [3, 0, 1]
期待される出力:
expected = 2
入力:
std::vector<long long> numbers = {3, 0, 1};
期待される出力:
long long expected = 2;
入力:
long[] numbers = new long[] {3, 0, 1};
期待される出力:
long expected = 2;
解説
n = 3, so the range is 0–3; 2 is missing.
入力:
numbers = [0]
期待される出力:
expected = 1
入力:
std::vector<long long> numbers = {0};
期待される出力:
long long expected = 1;
入力:
long[] numbers = new long[] {0};
期待される出力:
long expected = 1;
解説
n = 1 and the range is 0–1; 1 is missing.
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
The numbers should match the full range from 0 through n except for one hole.
ヒント 2
Compare what the complete range would total against what the list actually totals.
ヒント 3
Watch for the case where the missing value is 0 or n.
目安の計算量
O(n) time, O(1) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。