Torna alle sfide
Facile 0 risolte 0% di accettazione

Flatten a 2D Array

Combine the rows of a 2D integer array into one array.

Cosa imparerai

  • Scorrere righe e colonne
  • Aggiungere i valori a una sola lista
  • Mantenere l'ordine originale

Problema

Combine the rows of a 2D integer array into one array. Read rows from top to bottom and integers within each row from left to right. Skip empty rows. Preserve repeated integers and their order. Rows may have different lengths. There are exactly two array levels: rows contain only integers, with no null values or deeper lists.

Implement flatten_nested_list(values).

Input

values: The integer rows to combine, in order.

Output

Return all integers in row order. Return an empty array if there are no integers.

Vincoli

0 ≤ number of rows ≤ 10,000. At most 10,000 integers in total. Each integer is between −1,000,000,000 and 1,000,000,000. Rows may be empty or have different lengths.

Esempi

Esempio 1
Input:
values = [
    [1, 2],
    [],
    [3, 4]
]

Output atteso:
expected = [1, 2, 3, 4]
Input:
std::vector<std::vector<long long>> values = {
    {1, 2},
    {},
    {3, 4}
};

Output atteso:
std::vector<long long> expected = {1, 2, 3, 4};
Input:
long[][] values = new long[][] {
    new long[] {1, 2},
    new long[] {},
    new long[] {3, 4}
};

Output atteso:
long[] expected = new long[] {1, 2, 3, 4};

Spiegazione

Read 1 and 2 from the first row. Skip the empty second row. Append 3 and 4 from the last row.

Esempio 2
Input:
values = [
    [],
    []
]

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

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

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

Spiegazione

Both rows are empty, so there are no integers to append.

Come affrontarlo

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

Suggerimento 1

Scorri le righe in ordine e aggiungi ogni intero che incontri.

Suggerimento 2

Le righe vuote non aggiungono nulla, ma mantieni l’ordine di tutti i valori delle righe non vuote.

Suggerimento 3

L’input ha solo due livelli, quindi non serve alcuna flattening ricorsiva.

Complessità attesa

tempo O(n), spazio aggiuntivo O(n)

Riferimenti

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

Impara dagli altri

Soluzioni della community

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