코테/프로그래머스
[프로그래머스/Lv. 0] 2차원으로 만들기
imname1am
2023. 2. 7. 18:01
반응형
내 코드 (틀림)
class Solution {
public int[][] solution(int[] num_list, int n) {
int[][] answer = new int[num_list.length / n][n];
for(int i=0 ; i < num_list.length / n ; i++) {
for(int j=0 ; j < n ; j++) {
answer[i][j] = num_list[j];
}
}
return answer;
}
}
2차원 배열 사이즈는 맞게 했다만... 값이 제대로 안 들어갔음..
그렇다면 num_list[j]
여기를 수정해줘야하는 것이 분명한데....
내 코드 (정답)
class Solution {
public int[][] solution(int[] num_list, int n) {
int[][] answer = new int[num_list.length / n][n];
int cnt = 0;
for(int i=0 ; i < num_list.length / n ; i++) {
for(int j=0 ; j < n ; j++) {
answer[i][j] = num_list[cnt];
cnt++;
}
}
return answer;
}
}
변수 cnt를 만들고 두 번째 for문 안에서 num_list[cnt];
와 cnt++;
를 해줘야 했던...
다른 코드
class Solution {
public int[][] solution(int[] num_list, int n) {
int[][] answer = {};
int length = num_list.length;
answer = new int[length/n][n];
for(int i=0; i<length; i++){
answer[i/n][i%n] = num_list[i];
}
return answer;
}
}
10번째 줄... answer[i/n][i%n] = num_list[i];
나는 이 생각을 할 수 없었다....😂
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
반응형