|
| 1 | +/* |
| 2 | +时间:2019年12月20日 16:19:32 |
| 3 | +题目:Given n and m which are the dimensions of a matrix initialized by zeros |
| 4 | +and given an array indices where indices[i] = [ri, ci]. |
| 5 | +For each pair of [ri, ci] you have to increment all cells in row ri and column ci by 1 |
| 6 | +题意:将ri行加一,ci列加一 |
| 7 | +*/ |
| 8 | + |
| 9 | +#include<vector> |
| 10 | +#include<iostream> |
| 11 | +using namespace std; |
| 12 | +/* |
| 13 | +Runtime: 4 ms, faster than 83.07% of C++ online submissions for Cells with Odd Values in a Matrix. |
| 14 | +Memory Usage: 9.2 MB, less than 100.00% of C++ online submissions for Cells with Odd Values in a Matrix. |
| 15 | +*/ |
| 16 | +#define MAXN 55 |
| 17 | +#define MAXM 55 |
| 18 | +int cells[MAXN][MAXM]; |
| 19 | +int oddCells_1(int n, int m, vector<vector<int>>& indices) {//直接暴力求解 |
| 20 | + int odd = 0; |
| 21 | + for (int i = 0; i < n; i++) |
| 22 | + for (int j = 0; j < m; j++) |
| 23 | + cells[i][j] = 0; |
| 24 | + for (size_t i = 0; i < indices.size(); i++) { |
| 25 | + int a = indices[i][0]; |
| 26 | + int b = indices[i][1]; |
| 27 | + for (int i = 0; i < m; i++) |
| 28 | + cells[a][i]++; |
| 29 | + for (int i = 0; i < n; i++) |
| 30 | + cells[i][b]++; |
| 31 | + } |
| 32 | + for (int i = 0; i < n; i++) |
| 33 | + for (int j = 0; j < m; j++) |
| 34 | + if (cells[i][j] % 2 != 0) |
| 35 | + odd++; |
| 36 | + return odd; |
| 37 | +} |
| 38 | +/* |
| 39 | +Runtime: 0 ms, faster than 100.00% of C++ online submissions for Cells with Odd Values in a Matrix. |
| 40 | +Memory Usage: 9.3 MB, less than 100.00% of C++ online submissions for Cells with Odd Values in a Matrix. |
| 41 | +*/ |
| 42 | +int oddCells_2(int n, int m, vector<vector<int>>& indices) { |
| 43 | + vector<int> oddRows; |
| 44 | + vector<int> oddCols; |
| 45 | + //初始化所有行与列,0是偶数 |
| 46 | + oddRows.assign(n, 0); |
| 47 | + oddCols.assign(m, 0); |
| 48 | + |
| 49 | + |
| 50 | + for (const auto &elem : indices) { |
| 51 | + oddRows[elem[0]] = 1 - oddRows[elem[0]]; |
| 52 | + oddCols[elem[1]] = 1 - oddCols[elem[1]]; |
| 53 | + } |
| 54 | + //统计奇数的列数 |
| 55 | + int numOddCols = 0; |
| 56 | + for (const auto c : oddCols)//这种写法会比下方速度快 |
| 57 | + numOddCols += c; |
| 58 | + /*for (size_t i = 0; i < oddCols.size(); i++) |
| 59 | + if (oddCols[i] == 1) |
| 60 | + numOddCols++;*/ |
| 61 | + |
| 62 | + int numEvenCols = m - numOddCols; |
| 63 | + |
| 64 | + //输出奇数个数 |
| 65 | + int Odd = 0; |
| 66 | + for (auto r:oddRows) |
| 67 | + Odd += r ? numEvenCols : numOddCols; |
| 68 | + return Odd; |
| 69 | +} |
| 70 | + |
| 71 | +int main() { |
| 72 | + vector<vector<int>> indices = { {1,1},{0,0} }; |
| 73 | + vector<vector<int>> indices2 = { { 0,1 },{ 1,1 } }; |
| 74 | + int odd1=oddCells_1(2, 2, indices); |
| 75 | + int odd2= oddCells_2(2, 3, indices2); |
| 76 | + cout << odd2; |
| 77 | +} |
| 78 | + |
0 commit comments