簡単 2件解決済み 正答率66.7%

Missing Number

Find the one number missing from 0..n.

このチャレンジで学べること

  • Compute the expected sum of 0..n
  • Find the missing value from the difference
  • Solve it in one pass without sorting

問題

翻訳を表示

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

例

例 1
入力:
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.

例 2
入力:
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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 HJhettory Jurash Python 784 ms - 4/5 コードを見る
2 KKKaneki Ken Python 874 ms - 3/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意:下に2件の全解答あり まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。