Problème
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.
Contraintes
0 ≤ n ≤ 100,000
Exemples
Entrée :
numbers = [3, 0, 1]
Sortie attendue :
expected = 2
Entrée :
std::vector<long long> numbers = {3, 0, 1};
Sortie attendue :
long long expected = 2;
Entrée :
long[] numbers = new long[] {3, 0, 1};
Sortie attendue :
long expected = 2;
Explication
n = 3, so the range is 0–3; 2 is missing.
Entrée :
numbers = [0]
Sortie attendue :
expected = 1
Entrée :
std::vector<long long> numbers = {0};
Sortie attendue :
long long expected = 1;
Entrée :
long[] numbers = new long[] {0};
Sortie attendue :
long expected = 1;
Explication
n = 1 and the range is 0–1; 1 is missing.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
The numbers should match the full range from 0 through n except for one hole.
Indice 2
Compare what the complete range would total against what the list actually totals.
Indice 3
Watch for the case where the missing value is 0 or n.
Complexité attendue
O(n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.