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

Move Zeroes

Move every zero to the end while keeping the other order.

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

  • Move elements with a write pointer
  • Keep the relative order of non-zero values
  • Fill the remaining positions with zeros

โจทย์

ดูฉบับแปล

Return the list with all zeros moved to the end. The non-zero values keep their relative order.

Implement move_zeroes(numbers).

Input

numbers: The list of integers.

Output

Return the rearranged list.

เงื่อนไข

0 ≤ length ≤ 100,000

ตัวอย่าง

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

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

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

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

คำอธิบาย

1, 3, 12 keep their order and the two zeros go last: [1, 3, 12, 0, 0].

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

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

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

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

คำอธิบาย

Only zeros: the list stays [0, 0].

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

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

คำใบ้ 1

Non-zero values should keep their order while zeros drift to the end.

คำใบ้ 2

A two-pointer or write-index approach lets you rebuild the list in one pass.

คำใบ้ 3

Do not reorder the non-zero values when compacting them.

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

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

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

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

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

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

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

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