ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

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

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

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก