https://programmers.co.kr/learn/courses/30/lessons/12950
코딩테스트 연습 - 행렬의 덧셈 | 프로그래머스
행렬의 덧셈은 행과 열의 크기가 같은 두 행렬의 같은 행, 같은 열의 값을 서로 더한 결과가 됩니다. 2개의 행렬 arr1과 arr2를 입력받아, 행렬 덧셈의 결과를 반환하는 함수, solution을 완성해주세요. 제한 조건 행렬 arr1, arr2의 행과 열의 길이는 500을 넘지 않습니다. 입출력 예 arr1 arr2 return [[1,2],[2,3]] [[3,4],[5,6]] [[4,6],[7,9]] [[1],[2]] [[3],[4]] [[4],[
programmers.co.kr
방법 1
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Solution {
public int[][] solution(int[][] arr1, int[][] arr2) {
int[][] answer = new int[arr1.length][arr1[0].length];
for (int i = 0; i < answer.length; i++) {
for (int j = 0; j < answer[i].length; j++) {
answer[i][j] = arr1[i][j] + arr2[i][j];
}
}
return answer;
}
}
Colored by Color Scripter
|
방법 2 : 방어적인 다른 분 답안
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Solution {
int[][] solution(int[][] A, int[][] B) {
// 최대의 행,렬 구하기
int row = Math.max(A.length, B.length);
int col = Math.max(A[0].length, B[0].length);
int[][] answer = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
answer[i][j] = A[i][j] + B[i][j];
}
}
return answer;
}
}
Colored by Color Scripter
|
행과 열의 크기가 같은 두 행렬
문제에서 제약사항을 두었지만,
좀 더 안전하게 짠 분이 있어서 공유한다.
두 행렬에서 최대의 행과 열을 구하여 답안 행렬 만들기
'Algorithm > 프로그래머스' 카테고리의 다른 글
[프로그래머스]해시 : 완주하지 못한 선수 (level 1) (0) | 2019.11.08 |
---|---|
[프로그래머스]연습문제 : x만큼 간격이 있는 n개의 숫자 (level 1) (0) | 2019.11.07 |
[프로그래머스]연습문제 : 핸드폰 번호 가리기 (level 1) (0) | 2019.11.07 |
[프로그래머스]연습문제 : 하샤드 수 (level 1) (0) | 2019.11.07 |
[프로그래머스]연습문제 : 콜라츠 추측 (level 1) (0) | 2019.11.07 |
댓글