Fácil 0 resolvidos 0% de aceitação

Flatten a 2D Array

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

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

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.

Exemplos

Exemplo 1
Entrada:
values = [
    [1, 2],
    [],
    [3, 4]
]

Saída esperada:
expected = [1, 2, 3, 4]
Entrada:
std::vector<std::vector<long long>> values = {
    {1, 2},
    {},
    {3, 4}
};

Saída esperada:
std::vector<long long> expected = {1, 2, 3, 4};
Entrada:
long[][] values = new long[][] {
    new long[] {1, 2},
    new long[] {},
    new long[] {3, 4}
};

Saída esperada:
long[] expected = new long[] {1, 2, 3, 4};

Explicação

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

Exemplo 2
Entrada:
values = [
    [],
    []
]

Saída esperada:
expected = []
Entrada:
std::vector<std::vector<long long>> values = {
    {},
    {}
};

Saída esperada:
std::vector<long long> expected = {};
Entrada:
long[][] values = new long[][] {
    new long[] {},
    new long[] {}
};

Saída esperada:
long[] expected = new long[] {};

Explicação

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

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

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

Dica 2

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

Dica 3

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

Complexidade esperada

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

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.