|
| 1 | +package com.fishercoder.solutions.secondthousand; |
| 2 | + |
| 3 | +import java.util.PriorityQueue; |
| 4 | + |
| 5 | +public class _1605 { |
| 6 | + public static class Solution1 { |
| 7 | + /** |
| 8 | + * My completely original solution: |
| 9 | + * 1. sort out your logic with a pen and paper first, greedy algorithm should be the way to go; |
| 10 | + * 2. each time, take out the minimum value from both rowSet and colSet, put that entire value onto the result grid, |
| 11 | + * then deduct that value from the other set if they are not equal, put it back into the minHeap, repeat until both minHeaps are empty; |
| 12 | + */ |
| 13 | + public int[][] restoreMatrix(int[] rowSum, int[] colSum) { |
| 14 | + //form two minHeaps, use their values to sort |
| 15 | + PriorityQueue<int[]> rowMinHeap = new PriorityQueue<>((a, b) -> a[1] - b[1]); |
| 16 | + for (int i = 0; i < rowSum.length; i++) { |
| 17 | + rowMinHeap.offer(new int[]{i, rowSum[i]}); |
| 18 | + } |
| 19 | + PriorityQueue<int[]> colMinHeap = new PriorityQueue<>((a, b) -> a[1] - b[1]); |
| 20 | + for (int j = 0; j < colSum.length; j++) { |
| 21 | + colMinHeap.offer(new int[]{j, colSum[j]}); |
| 22 | + } |
| 23 | + |
| 24 | + int[][] result = new int[rowSum.length][colSum.length]; |
| 25 | + while (!colMinHeap.isEmpty() && !rowMinHeap.isEmpty()) { |
| 26 | + int[] minRow = rowMinHeap.poll(); |
| 27 | + int[] minCol = colMinHeap.poll(); |
| 28 | + if (minRow[1] < minCol[1]) { |
| 29 | + result[minRow[0]][minCol[0]] = minRow[1]; |
| 30 | + colMinHeap.offer(new int[]{minCol[0], minCol[1] - minRow[1]}); |
| 31 | + } else if (minRow[1] > minCol[1]) { |
| 32 | + result[minRow[0]][minCol[0]] = minCol[1]; |
| 33 | + rowMinHeap.offer(new int[]{minRow[0], minRow[1] - minCol[1]}); |
| 34 | + } else { |
| 35 | + //the min values from row and col are equal |
| 36 | + result[minRow[0]][minCol[0]] = minCol[1]; |
| 37 | + } |
| 38 | + } |
| 39 | + return result; |
| 40 | + } |
| 41 | + } |
| 42 | +} |
0 commit comments