zoukankan      html  css  js  c++  java
  • 【LeetCode】-- 73. Set Matrix Zeroes

    问题描述:将二维数组中值为0的元素,所在行或者列全set为0;https://leetcode.com/problems/set-matrix-zeroes/

    问题分析:题中要求用 constant space 的辅助空间。自然想到位优化。一个int可以存储31个元素的信息。这里刚好用到了字符串论文里面常用的优化处理方法。类似桶分的思想。好吧,这么看来这长时间的论文没白看。

    附上代码:

     1 void setZeroes(vector<vector<int>>& matrix) {
     2         int n = matrix.size(), m = matrix[0].size();
     3         int *row = (int*) malloc((n / 31 + 2) * sizeof(int));
     4         int *col = (int*) malloc((m / 31 + 2) * sizeof(int));
     5        
     7         for(int i = 0; i < n / 31 + 2; i ++) row[i] = 0;
     8         for(int i = 0; i < m / 31 + 2; i ++) col[i] = 0;
     9         
    10         int posInt , posBit ;
    11         for(int i = 0; i < n; i ++){
    12             for(int j = 0; j < m; j ++){
    13                 if(matrix[i][j] == 0){
    14                     cout<<" i = "<<i <<"  j = "<<j <<endl;
    15                     posInt = i / 31, posBit = i % 31;
    16                     row[posInt] |= (1 << posBit);
    17                     posInt = j / 31, posBit = j % 31;
    18                     col[posInt] |= (1 << posBit);
    19                 }
    20             }
    21         }
    22         
    23         for(int i = 0; i < n; i ++){
    24             posInt = i / 31;posBit = i % 31;
    25             if(row[posInt] & (1 << posBit)){
    26                 for(int j = 0; j < m; j ++){
    27                     matrix[i][j] = 0;
    28                 }
    29             }
    30         }
    31         
    32         for(int i = 0; i < m; i ++){
    33             posInt = i / 31;posBit = i % 31;
    34             if(col[posInt] & (1 << posBit)){
    35                 for(int j = 0; j < n; j ++){
    36                     matrix[j][i] = 0;
    37                 }
    38             }
    39         }
    40     }

    反思:本来是一个很简单的问题medium难度的,可是遇到了一个大坑,就是我开始使用memset函数对动态数组row和col进行初始化。大数据上出现了离奇的bug,最后找了很久才定位到这个初始化函数这里,使用for循环手动初始化,问题得到解决。

      memset 是用来初始化字符串的,但因为Ascii (0) = NULL,NULL的Ascii刚好是0,所以可以用来给数组初始化成0,但是这里要注意初始化的大小(n * sizeof int),不要被初始化char[]的时候,直接使用的sizeof(数组名)混淆,这里*row只是一个指向n个int区域的指针,其大小还是一个int的size。 

  • 相关阅读:
    70.BOM
    69.捕获错误try catch
    68.键盘事件
    523. Continuous Subarray Sum
    901. Online Stock Span
    547. Friend Circles
    162. Find Peak Element
    1008. Construct Binary Search Tree from Preorder Traversal
    889. Construct Binary Tree from Preorder and Postorder Traversal
    106. Construct Binary Tree from Inorder and Postorder Traversal
  • 原文地址:https://www.cnblogs.com/luntai/p/5315295.html
Copyright © 2011-2022 走看看