Tutte le sfide
Facile 1 risolta 100.0% di accettazione

Flatten a 2D Array

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

Cosa imparerai

  • Loop over rows and columns
  • Append values into a single list
  • Keep the original order

Problema

Mostra traduzione

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

Traverse the rows in order and append each integer you encounter.

Suggerimento 2

Empty rows contribute nothing, but preserve the order of all values from nonempty rows.

Suggerimento 3

The input is only two levels deep, so no recursive flattening is needed.

Complessità attesa

O(n) time, O(n) 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.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 RCRiccardo Corti Python 1,249 ms - 4/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 1 soluzione completa sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.