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

Remove Duplicates

Keep only the first occurrence of each value.

สิ่งที่คุณจะได้เรียนรู้

  • Track seen values with a set
  • Keep the first occurrence of each value
  • Preserve the original order

โจทย์

ดูฉบับแปล

Return the list with repeated values removed, keeping the first occurrence of each value in its original order.

Implement remove_duplicates(numbers).

Input

numbers: The list of integers.

Output

Return the list without duplicates.

เงื่อนไข

0 ≤ length ≤ 100,000

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
numbers = [3, 1, 3, 2, 1]

ผลลัพธ์ที่คาดหวัง:
expected = [3, 1, 2]
อินพุต:
std::vector<long long> numbers = {3, 1, 3, 2, 1};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {3, 1, 2};
อินพุต:
long[] numbers = new long[] {3, 1, 3, 2, 1};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {3, 1, 2};

คำอธิบาย

Keep 3, 1, then 2; the later 3 and 1 are dropped: [3, 1, 2].

ตัวอย่างที่ 2
อินพุต:
numbers = [7, 7, 7]

ผลลัพธ์ที่คาดหวัง:
expected = [7]
อินพุต:
std::vector<long long> numbers = {7, 7, 7};

ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {7};
อินพุต:
long[] numbers = new long[] {7, 7, 7};

ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {7};

คำอธิบาย

Only the first 7 stays: [7].

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Keep the first time each value appears and ignore later repeats.

คำใบ้ 2

A set or similar lookup helps you decide quickly whether a value was already seen.

คำใบ้ 3

Preserve the original order of the first occurrences, not sorted order.

ความซับซ้อนที่คาดหวัง

O(n) time, O(n) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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