Facile 0 risolte 0% di accettazione

Move Zeroes

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

0 ≤ length ≤ 100,000

Esempi

Esempio 1
Input:
numbers = [0, 1, 0, 3, 12]

Output atteso:
expected = [1, 3, 12, 0, 0]
Input:
std::vector<long long> numbers = {0, 1, 0, 3, 12};

Output atteso:
std::vector<long long> expected = {1, 3, 12, 0, 0};
Input:
long[] numbers = new long[] {0, 1, 0, 3, 12};

Output atteso:
long[] expected = new long[] {1, 3, 12, 0, 0};

Spiegazione

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

Esempio 2
Input:
numbers = [0, 0]

Output atteso:
expected = [0, 0]
Input:
std::vector<long long> numbers = {0, 0};

Output atteso:
std::vector<long long> expected = {0, 0};
Input:
long[] numbers = new long[] {0, 0};

Output atteso:
long[] expected = new long[] {0, 0};

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.