โจทย์
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
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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน