넘치게 채우기
[LeetCode] 2022. Convert 1D Array Into 2D Array 본문
leetcode - Convert 1D Array Into 2D Array
문제 유형 : 행렬, 배열, 구현
문제 난이도 : Easy
문제
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original.
The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on.
Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
1차원배열 original과 두 정수 m, n이 주어진다.
original을 m * n의 2차원배열로 변환하시오.
단, 만들 수 없으면 빈 배열을 반환하시오.
풀이
m x n짜리 2D배열을 만든다.
arr[i][j]의 값은 original[i * n + j]의 값을 넣어주면 된다.
배열을 본질적으로 생각해보자.
코드
C++
#pragma GCC optimize("03", "unroll-loops");
static const int __ = [](){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
return 0;
}();
class Solution {
public:
vector<vector<int>> construct2DArray(vector<int>& original, int m, int n) {
vector<vector<int>> ans(m, vector<int>(n));
if(m * n != original.size()) return {};
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
ans[i][j] = original[n * i + j];
}
}
return ans;
}
};
GO
func construct2DArray(original []int, m int, n int) [][]int {
if len(original) != m*n {
return nil
}
ans := make([][]int, m)
for i := 0; i < m; i++ {
ans[i] = make([]int, n)
for j := 0; j < n; j++ {
ans[i][j] = original[i*n+j]
}
}
return ans
}
'PS > LeetCode' 카테고리의 다른 글
[LeetCode] 1945. Sum of Digits of String After Convert (0) | 2024.09.03 |
---|---|
[LeetCode] 1894. Find the Student that Will Replace the Chalk (0) | 2024.09.02 |
[LeetCode] 2699. Modify Graph Edge Weights (0) | 2024.08.30 |
[LeetCode] 947. Most Stones Removed with Same Row or Column (0) | 2024.08.29 |
[LeetCode] 1905. Count Sub Islands (0) | 2024.08.28 |