Dễ 1 người đã giải Tỷ lệ chấp nhận 100.0%

Flatten a 2D Array

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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.

Ví dụ

Ví dụ 1
Đầu vào:
values = [
    [1, 2],
    [],
    [3, 4]
]

Kết quả mong đợi:
expected = [1, 2, 3, 4]
Đầu vào:
std::vector<std::vector<long long>> values = {
    {1, 2},
    {},
    {3, 4}
};

Kết quả mong đợi:
std::vector<long long> expected = {1, 2, 3, 4};
Đầu vào:
long[][] values = new long[][] {
    new long[] {1, 2},
    new long[] {},
    new long[] {3, 4}
};

Kết quả mong đợi:
long[] expected = new long[] {1, 2, 3, 4};

Giải thích

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

Ví dụ 2
Đầu vào:
values = [
    [],
    []
]

Kết quả mong đợi:
expected = []
Đầu vào:
std::vector<std::vector<long long>> values = {
    {},
    {}
};

Kết quả mong đợi:
std::vector<long long> expected = {};
Đầu vào:
long[][] values = new long[][] {
    new long[] {},
    new long[] {}
};

Kết quả mong đợi:
long[] expected = new long[] {};

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 RCRiccardo Corti Python 1,249 ms - 4/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.