ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก