LeetCode1252. 奇数值单元格的数目

//1252. 奇数值单元格的数目
/*
* 1、暴力做法:直接创建一个 n*m 的矩阵,然后模拟,最后遍历矩阵,计数
*   复杂度:(m+n)*indices.length+m*n -> 12500
*   代码就不放了
* 2、巧妙,但是复杂度比较高的方法:
*   针对矩阵中的每个元素坐标,他最后的数字=自己的坐标在坐标数组中出现了多少次来决定的
*   比如说:坐标数组有:[1,1] [2,1]
*   1)那么[0,1]的0在坐标数组的横坐标中出现了0次,1在坐标数组的纵坐标中出现了2次
*     所以[0,1]最后的数字就是2。
*   2)同样,[1,1]的1在坐标数组的横坐标中出现了2次,1在坐标数组的纵坐标中出现了2次
*     所以[1,1]最后的数字就是3。
*   复杂度:m*n*indices.length -> 250000
* 3、巧妙,并且复杂度比较低的做法:
*   使用两个数组,分别记录每一行(列)上出现坐标的次数
*   然后遍历矩阵的每个坐标,将横纵两个数组中对应的值相加就是这个坐标最后的数字
*   复杂度:indices.length + m*n -> 2600
*/
//方法二
class Solution {
     
public:
  int oddCells(int n, int m, vector<vector<int>>& indices) {
     
    int ans = 0;
    for (int i = 0; i < n; i++) {
     
      for (int j = 0; j < m; j++) {
     
        int cnt = 0;
        for (auto x : indices) {
     
          if (x[0] == i) cnt++;
          if (x[1] == j) cnt++;
        }
        if (cnt & 1) ans++;
      }
    }
    return ans;
  }
};
//方法三
class Solution {
     
public:
  int oddCells(int n, int m, vector<vector<int>>& indices) {
     
    int row[50] = {
      0 };
    int col[50] = {
      0 };
    for (auto x : indices) {
     
      row[x[0]]++;
      col[x[1]]++;
    }
    int ans = 0;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        if ((row[i] + col[j]) & 1) ans++;
    return ans;
  }
};

你可能感兴趣的:(#,LeetCode,1024程序员节)