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

Split a List Into Chunks

Cut a list into consecutive groups of a fixed size, with a shorter last group if needed.

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

  • Step through a list in fixed-size jumps
  • Take slices that may be shorter at the end
  • Group data for paging or batch processing

Đề bài

Xem bản dịch

Splitting data into fixed-size chunks is how programs page results, batch database writes or send data in packets.

Given a list and a chunk size, cut the list into consecutive chunks of exactly size values, in order. The last chunk holds whatever is left and may be shorter.

Implement split_into_chunks(values, size).

Input

values: The list to split.

size: The chunk size.

Output

Return the list of chunks. An empty list gives no chunks.

Ràng buộc

0 ≤ number of values ≤ 10,000

1 ≤ size ≤ 10,000

Ví dụ

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

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

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

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

Giải thích

Groups of 3: [1, 2, 3] and [4, 5, 6], and the leftover 7 forms a last, shorter chunk.

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

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

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

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

Giải thích

The size is larger than the list, so everything fits in one chunk: [[8, 9]].

Hướng tiếp cận

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

Gợi ý 1

Start positions are 0, size, 2·size, and so on.

Gợi ý 2

Take a slice from each start position up to start + size.

Gợi ý 3

The last slice may be shorter, and an empty list gives no chunks at all.

Độ 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 835 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.