簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。