簡単 1件解決済み 正答率100.0%

Flatten a 2D Array

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

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.

例

例 1
入力:
values = [
    [1, 2],
    [],
    [3, 4]
]

期待される出力:
expected = [1, 2, 3, 4]
入力:
std::vector<std::vector<long long>> values = {
    {1, 2},
    {},
    {3, 4}
};

期待される出力:
std::vector<long long> expected = {1, 2, 3, 4};
入力:
long[][] values = new long[][] {
    new long[] {1, 2},
    new long[] {},
    new long[] {3, 4}
};

期待される出力:
long[] expected = new long[] {1, 2, 3, 4};

解説

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

例 2
入力:
values = [
    [],
    []
]

期待される出力:
expected = []
入力:
std::vector<std::vector<long long>> values = {
    {},
    {}
};

期待される出力:
std::vector<long long> expected = {};
入力:
long[][] values = new long[][] {
    new long[] {},
    new long[] {}
};

期待される出力:
long[] expected = new long[] {};

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを1つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

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

# コーダー 言語 時間 メモリ AI 評価 解答
1 RCRiccardo Corti Python 1,249 ms - 4/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が1件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。