-
64일 (1605. Find Valid Matrix Given Row and Column Sums) matrix지식/알고리즘 2023. 11. 23. 08:01
You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.
Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.
Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.
Example 1:
Input: rowSum = [3,8], colSum = [4,7] Output: [[3,0], [1,7]] Explanation: 0th row: 3 + 0 = 3 == rowSum[0] 1st row: 1 + 7 = 8 == rowSum[1] 0th column: 3 + 1 = 4 == colSum[0] 1st column: 0 + 7 = 7 == colSum[1] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: [[1,2], [3,5]]
Example 2:
Input: rowSum = [5,7,10], colSum = [8,6,8] Output: [[0,5,0], [6,1,0], [2,0,8]]
Constraints:
- 1 <= rowSum.length, colSum.length <= 500
- 0 <= rowSum[i], colSum[i] <= 10^8
- sum(rowSum) == sum(colSum)
- 접근방법
어떻게 구현해야 할지 30분정도 생각해보았다.
rowSum.length == colSum.length 이 조건 덕분에 주어진 매개변수에서 리턴될 수 있는 값이 어려개가 존재할 수 있었다.
하지만 rowSum과 colSum의 값이 어떻게 되든지 동일한 유형으로 답을 리턴하려고 생각해보았다.
예를들어, rowSum = {2, 7, 6} 그리고 rowCol = {3, 5, 7}이 주어진다면 sum(rowSum) == sum(rowCol) == 15로 가능하다. 그리고
1. (rowSum.length * colSum.length) 크기의 2차원 배열 arr를 초기화 하였다.
2. 현재 arr[i][j]에 해당하는 rowSum[i]와 rowCol[i]의 값을 비교하여 둘 중 더 작은 값 value를 arr[i][j]에 넣어주고
rowSum[i]와 rowCol[i]의 값을 value만큼 빼주었다.
-위 2번 방법으로 2차원배열 arr를 끝까지 순회하면 된다.
- 코드
class Solution { public int[][] restoreMatrix(int[] rowSum, int[] colSum) { int [][] arr = new int[rowSum.length][colSum.length]; // 1 for(int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[0].length; j++) { // 2 int value = Math.min(rowSum[i], colSum[j]); arr[i][j] = value; rowSum[i] -= value; colSum[j] -= value; } } return arr; } }
확실히 전과 다르게 많이 늘었다.
문제를 보고, 메모지에 범용적으로 돌아갈만한 공식을 적으면서 생각해보고
내 실력으로 구현 가능할지 생각해보면 되는 것 같다.
https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/
Find Valid Matrix Given Row and Column Sums - LeetCode
Can you solve this real interview question? Find Valid Matrix Given Row and Column Sums - You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements
leetcode.com
'지식 > 알고리즘' 카테고리의 다른 글
66일 (2133. Check if Every Row and Column Contains All Numbers) matrix (0) 2023.11.25 65일 (885. Spiral Matrix III) matrix (0) 2023.11.24 63일 (59. Spiral Matrix II) matrix (0) 2023.11.22 62일 (2326. Spiral Matrix IV) matrix 다른 접근필요 (0) 2023.11.21 61일 (289. Game of Life) matrix 어려움 (0) 2023.11.20