LeetCode 73: Set Matrix Zeroes

LeetCode 73: Set Matrix Zeroes

  • [Problem Link 🔗](#Problem Link 🔗)
  • [Solution Overview 🧭](#Solution Overview 🧭)
  • [Solution 1: Additional Arrays (O(m+n) Space)](#Solution 1: Additional Arrays (O(m+n) Space))
    • [Algorithm Idea](#Algorithm Idea)
    • [Important Points](#Important Points)
    • [Java Implementation](#Java Implementation)
    • [Time & Space Complexity](#Time & Space Complexity)
  • [Solution 2: In-place Marking (O(1) Space)](#Solution 2: In-place Marking (O(1) Space))
    • [Algorithm Idea](#Algorithm Idea)
    • [Important Points](#Important Points)
    • [Java Implementation](#Java Implementation)
    • [Time & Space Complexity](#Time & Space Complexity)
  • [Solution 3: Optimized In-place (Single Variable)](#Solution 3: Optimized In-place (Single Variable))
    • [Algorithm Idea](#Algorithm Idea)
    • [Important Points](#Important Points)
    • [Java Implementation](#Java Implementation)
    • [Time & Space Complexity](#Time & Space Complexity)
  • [Solution Comparison 📊](#Solution Comparison 📊)
  • [Summary 📝](#Summary 📝)

LeetCode 73: Set Matrix Zeroes

Solution Overview 🧭

Given an m x n matrix, if an element is 0, set its entire row and column to 0. You must do it in-place.

Constraints:

m == matrix.length

n == matrix[i].length

1 <= m, n <= 200

-2³¹ <= matrix[i][j] <= 2³¹ - 1

Common approaches include:

Additional Arrays: Use separate arrays to mark rows and columns to be zeroed

In-place Marking: Use first row and first column as markers

Bit Manipulation: Use bits to track rows and columns (for smaller matrices)

Solution 1: Additional Arrays (O(m+n) Space)

Algorithm Idea

Create two boolean arrays: zeroRows and zeroCols

First pass: Mark which rows and columns contain zeros

Second pass: Set matrix elements to zero based on the markers

Important Points

Straightforward and easy to understand

Requires O(m + n) extra space

Time complexity is optimal

Java Implementation

java 复制代码
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        
        boolean[] zeroRows = new boolean[m];
        boolean[] zeroCols = new boolean[n];
        
        // Mark rows and columns that contain zeros
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 0) {
                    zeroRows[i] = true;
                    zeroCols[j] = true;
                }
            }
        }
        
        // Set rows to zero
        for (int i = 0; i < m; i++) {
            if (zeroRows[i]) {
                for (int j = 0; j < n; j++) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        // Set columns to zero
        for (int j = 0; j < n; j++) {
            if (zeroCols[j]) {
                for (int i = 0; i < m; i++) {
                    matrix[i][j] = 0;
                }
            }
        }
    }
}

Time & Space Complexity

Time Complexity: O(m × n)

Space Complexity: O(m + n)

Solution 2: In-place Marking (O(1) Space)

Algorithm Idea

Use first row and first column as markers

Use two additional variables to track if first row/column originally had zeros

First pass: Mark zeros in the first row and column

Second pass: Use markers to set zeros in the rest of the matrix

Finally: Handle first row and column based on the tracking variables

Important Points

Constant extra space (only 2 boolean variables)

More complex logic but space-optimal

Must handle first row/column separately

Java Implementation

java 复制代码
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        
        boolean firstRowZero = false;
        boolean firstColZero = false;
        
        // Check if first row has zero
        for (int j = 0; j < n; j++) {
            if (matrix[0][j] == 0) {
                firstRowZero = true;
                break;
            }
        }
        
        // Check if first column has zero
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) {
                firstColZero = true;
                break;
            }
        }
        
        // Use first row and column as markers
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        
        // Set zeros based on markers (excluding first row/column)
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        // Handle first row
        if (firstRowZero) {
            for (int j = 0; j < n; j++) {
                matrix[0][j] = 0;
            }
        }
        
        // Handle first column
        if (firstColZero) {
            for (int i = 0; i < m; i++) {
                matrix[i][0] = 0;
            }
        }
    }
}

Time & Space Complexity

Time Complexity: O(m × n)

Space Complexity: O(1)

Solution 3: Optimized In-place (Single Variable)

Algorithm Idea

Use first row as column markers

Use a single variable to track if first row has zero

First pass: Set markers and handle first row

Process in reverse order to avoid overwriting markers

Important Points

Most space-efficient (only 1 boolean variable)

Processes matrix from bottom-right to top-left

More complex but optimal for space

Java Implementation

java 复制代码
class Solution {
    public void setZeroes(int[][] matrix) {
        int m = matrix.length;
        int n = matrix[0].length;
        
        boolean firstRowHasZero = false;
        
        // Check first row and set markers
        for (int j = 0; j < n; j++) {
            if (matrix[0][j] == 0) {
                firstRowHasZero = true;
            }
        }
        
        // Use first row as column markers
        for (int i = 1; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        
        // Set zeros from bottom-right to avoid overwriting markers
        for (int i = m - 1; i >= 1; i--) {
            for (int j = n - 1; j >= 0; j--) {
                if (matrix[0][j] == 0 || matrix[i][0] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        
        // Handle first row
        if (firstRowHasZero) {
            for (int j = 0; j < n; j++) {
                matrix[0][j] = 0;
            }
        }
    }
}

Time & Space Complexity

Time Complexity: O(m × n)

Space Complexity: O(1)

Solution Comparison 📊

Summary 📝

Key Insight: Use the matrix itself to store information about which rows/columns need to be zeroed

Recommended Approach: Solution 2 (In-place Marking) provides the best balance between readability and space efficiency

Interview Tip: This problem tests your ability to optimize space usage while maintaining clarity

The in-place marking technique is a common pattern that appears in many matrix manipulation problems, making it valuable to understand thoroughly.

相关推荐
书源丶8 小时前
三十二、Java集合(一)——Collection与List全家桶
java·windows·list
AI人工智能+电脑小能手8 小时前
【大白话说Java面试题】【Java基础篇】第21题:HashMap和Hashtable的区别是什么
java·开发语言·面试·哈希算法·散列表·hash table
慕容卡卡9 小时前
Claude 使用神器(web页面)--CloudCLI UI
java·开发语言·前端·人工智能·ui·spring cloud
Sylvia-girl9 小时前
C++内存如何管理?
java·jvm·c++
shehuiyuelaiyuehao9 小时前
算法14,滑动窗口,找到字符串中所有字母异位词
算法
凯瑟琳.奥古斯特9 小时前
图论核心考点精讲
开发语言·数据结构·算法·排序算法·哈希算法
极创信息9 小时前
信创领域五种主流CPU架构(X86 / ARM / RISC-V / MIPS / LoongArch)
java·arm开发·数据库·spring boot·mysql·软件工程·risc-v
_日拱一卒9 小时前
LeetCode:146LRU缓存
java·开发语言
WolfGang0073219 小时前
代码随想录算法训练营 Day49 | 图论 part07
算法·图论
啦啦啦_99999 小时前
案例之 逻辑回归_癌症预测
算法·机器学习·逻辑回归