zoukankan      html  css  js  c++  java
  • 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?

    代码:

    题目很简单,就是矩阵中如果存在值为0的元素,就把该元素对应的行和列上面的元素全都改成0。

    思考了半天,还是遍历了两遍,复杂度至少在O(mn):

      public void setZeroes(int[][] matrix) {
             int i,j;
             ArrayList<Integer> row = new ArrayList<Integer>();
             ArrayList<Integer> col = new ArrayList<Integer>();        
             //第一个循环,遍历一遍,记录哪些行和哪些列需要改成0
             for (i=0;i < matrix.length;i++)
             { 
              for (j=0;j<matrix[i].length;j++)
              {
               if(matrix[i][j] == 0)
               {
                row.add(i);
                col.add(j);
               }
              }       
             }
           //第二个循环,又遍历一遍,根据需要变为0的行和列修改对应元素
             for (i=0;i < matrix.length;i++)
             { 
              for (j=0;j<matrix[i].length;j++)
              {
               if(row.contains(i)||col.contains(j))
               {
                matrix[i][j] =0;
    //            System.out.print("修改第"+i+"行,第"+j+"列");
               } 
              }       
             }
     
         }

    题目中提到算法复杂度可以小于 O(m + n),还在研究中...

  • 相关阅读:
    鼠标滑动察看
    jquery放大镜,可随意设置css
    常用的js插件配合滚轮事件左右滚动
    css的各种bug集合,主要针对ie6,7会出现
    ajax跨域请求及jsonp方式
    js随机生成一组指定区间的数组
    性能测试相关
    web窗体加载的过程。
    解密微软中间语言:MSIL
    .net应用程序版本控制
  • 原文地址:https://www.cnblogs.com/yuanzhaoyi/p/5724472.html
Copyright © 2011-2022 走看看