問題
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
例
入力:
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].
入力:
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 つずつ開いてみましょう。
ヒント 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用に調整されています。上記の説明と制約に従ってください。