모든 챌린지
쉬움 0명 해결 정답률 0%

Split a List Into Chunks

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

배우게 될 내용

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

문제

번역본 보기

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.

제약 조건

0 ≤ number of values ≤ 10,000

1 ≤ size ≤ 10,000

예시

예시 1
입력:
size = 3
values = [1, 2, 3, 4, 5, 6, 7]

예상 출력:
expected = [
    [1, 2, 3],
    [4, 5, 6],
    [7]
]
입력:
long long size = 3;
std::vector<long long> values = {1, 2, 3, 4, 5, 6, 7};

예상 출력:
std::vector<std::vector<long long>> expected = {
    {1, 2, 3},
    {4, 5, 6},
    {7}
};
입력:
long size = 3;
long[] values = new long[] {1, 2, 3, 4, 5, 6, 7};

예상 출력:
long[][] expected = new long[][] {
    new long[] {1, 2, 3},
    new long[] {4, 5, 6},
    new long[] {7}
};

설명

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

예시 2
입력:
size = 5
values = [8, 9]

예상 출력:
expected = [
    [8, 9]
]
입력:
long long size = 5;
std::vector<long long> values = {8, 9};

예상 출력:
std::vector<std::vector<long long>> expected = {
    {8, 9}
};
입력:
long size = 5;
long[] values = new long[] {8, 9};

예상 출력:
long[][] expected = new long[][] {
    new long[] {8, 9}
};

설명

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

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

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

힌트 2

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

힌트 3

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

예상 복잡도

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

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.