【貪心】B040_LC_重構 2 行二進制矩陣(構造 + 規定順序)

一、Problem

Given the following details of a matrix with n columns and 2 rows :

The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.
The sum of elements of the 0-th(upper) row is given as upper.
The sum of elements of the 1-st(lower) row is given as lower.
The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.
Your task is to reconstruct the matrix with upper, lower and colsum.

Return it as a 2-D integer array.

If there are more than one valid solution, any of them will be accepted.

If no valid solution exists, return an empty 2-D array.

Input: upper = 2, lower = 1, colsum = [1,1,1]
Output: [[1,1,0],[0,0,1]]
Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.

二、Solution

方法一:貪心構造

唉,還是不是很會寫這種構造題,遇到分類討論就想得很慢,生怕少分析一種情況,這裏就是卡在返回空列表的那一種情況,但分類討論的思想還是正確的:

  • colsum[i] 爲 2 時,不用想了,第 i 列都是 2
  • colsum[i] 爲 1 時,這個要小心,因爲有兩行,所以我們要規定一個順序,即遇到 1 時,1 先加到哪一行中。
  • colsum[i] 爲 0 時,也不用想,第 i 列全是 0
class Solution {
    public List<List<Integer>> reconstructMatrix(int up, int lo, int[] cs) {
        int n = cs.length, tot = 0;
        for (int i = 0; i < n; i++) {
            if (cs[i] == 2) {
                up--; lo--;
            } else if (cs[i] == 1)
                tot++; 
        }
        List<List<Integer>> ans = new LinkedList<>();
        if (up + lo != tot || up < 0 || lo < 0)
            return ans;
        List<Integer> u = new LinkedList<>(), l = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            if (cs[i] == 2) {
                u.add(1); l.add(1);
            } else if (cs[i] == 1) {
                if (up-- > 0) {
                    u.add(1);
                    l.add(0);
                } else if (lo-- > 0) {
                    u.add(0);
                    l.add(1);
                }
            } else {
                u.add(0); l.add(0);
            }
        }
        ans.add(u); 
        ans.add(l);
        return ans;
    }   
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(n)O(n)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章