Đề bài
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.
Ràng buộc
0 ≤ length ≤ 100,000
Ví dụ
Đầu vào:
numbers = [0, 1, 0, 3, 12]
Kết quả mong đợi:
expected = [1, 3, 12, 0, 0]
Đầu vào:
std::vector<long long> numbers = {0, 1, 0, 3, 12};
Kết quả mong đợi:
std::vector<long long> expected = {1, 3, 12, 0, 0};
Đầu vào:
long[] numbers = new long[] {0, 1, 0, 3, 12};
Kết quả mong đợi:
long[] expected = new long[] {1, 3, 12, 0, 0};
Giải thích
1, 3, 12 keep their order and the two zeros go last: [1, 3, 12, 0, 0].
Đầu vào:
numbers = [0, 0]
Kết quả mong đợi:
expected = [0, 0]
Đầu vào:
std::vector<long long> numbers = {0, 0};
Kết quả mong đợi:
std::vector<long long> expected = {0, 0};
Đầu vào:
long[] numbers = new long[] {0, 0};
Kết quả mong đợi:
long[] expected = new long[] {0, 0};
Giải thích
Only zeros: the list stays [0, 0].
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Non-zero values should keep their order while zeros drift to the end.
Gợi ý 2
A two-pointer or write-index approach lets you rebuild the list in one pass.
Gợi ý 3
Do not reorder the non-zero values when compacting them.
Độ phức tạp mong đợi
O(n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.