• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ArgenBarbie
博客园    首页    新随笔    联系   管理    订阅  订阅
73. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

 

1.

void setZeroes1(vector<vector<int> > &matrix) {
        
    int bRow = false, bCol=false;
        
    for (int r=0; r<matrix.size(); r++){
        for(int c=0; c<matrix[r].size(); c++){
            if (matrix[r][c]==0){
                if (r==0) bRow = true;
                if (c==0) bCol = true;
                matrix[0][c] = matrix[r][0] = 0;
            }
        }
    }
        
    for (int r=1; r<matrix.size(); r++){
        for(int c=1; c<matrix[r].size(); c++){
            if (matrix[0][c]==0 || matrix[r][0]==0) {
                matrix[r][c]=0;
            }
        }
    }
    if (bRow){
        for(int c=0; c<matrix[0].size(); c++) matrix[0][c] = 0;
    }
    if (bCol){
        for(int r=0; r<matrix.size(); r++) matrix[r][0] = 0;
    }

}

 

2.

用位来记第i行或列是否有0。

t = t | (1 << i)

posted on 2016-03-16 17:11  ArgenBarbie  阅读(153)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3