LeetCode的medium题集合(C++实现)十三
来源:互联网 发布:淘宝必买清单怎么写 编辑:程序博客网 时间:2024/04/29 19:10
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.
因为没有额外的空间,我们可以采用第一个0元素所在的行和列来保存0元素的信息。
void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(); int n = matrix[0].size(); int x = -1, y = -1; for (int i = 0; i<m; i++) { for (int j = 0; j<n; j++) { if (matrix[i][j] == 0) { if (x == -1 && y == -1) { x = i; y = j; } else { matrix[x][j] = 0; matrix[i][y] = 0; } } } } if (x == -1 || y == -1) return; for (int i = 0; i < n; i++) { if (i!=y&&matrix[x][i] == 0) { for (int j = 0; j < m; j++) { matrix[j][i] = 0; } } } for (int i = 0; i < m; i++) { if (i!=x&&matrix[i][y] == 0) { for (int j = 0; j < n; j++) { matrix[i][j] = 0; } } } for (int i = 0; i < m; i++) matrix[i][y] = 0; for (int j = 0; j < n; j++) matrix[x][j] = 0; }
2 Search a 2D Matrix
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.The first integer of each row is greater than the last integer of the previous row.
For example, Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
该题是一道比较简单的二分查找的题,只需将一维数组下标转为对应的二维数组下标。
bool searchMatrix(vector<vector<int>>& matrix, int target) { int m=matrix.size(); if(m==0) return false; int n=matrix[0].size(); int begin=0,end=m*n-1,mid=0,row=0,col=0; while(begin<=end) { mid=(begin+end)/2; row=mid/n; col=mid%n; if(matrix[row][col]==target) return true; else if(matrix[row][col]>target) end=mid-1; else begin=mid+1; } return false; }
0 0
- LeetCode的medium题集合(C++实现)十三
- LeetCode的medium题集合(C++实现)一
- LeetCode的medium题集合(C++实现)二
- LeetCode的medium题集合(C++实现)三
- LeetCode的medium题集合(C++实现)四
- LeetCode的medium题集合(C++实现)五
- LeetCode的medium题集合(C++实现)六
- LeetCode的medium题集合(C++实现)七
- LeetCode的medium题集合(C++实现)八
- LeetCode的medium题集合(C++实现)九
- LeetCode的medium题集合(C++实现)十
- LeetCode的medium题集合(C++实现)十一
- LeetCode的medium题集合(C++实现)十二
- LeetCode的medium题集合(C++实现)十四
- LeetCode的medium题集合(C++实现)十五
- LeetCode的medium题集合(C++实现)十六
- LeetCode的medium题集合(C++实现)十七
- [leetcode]55. Jump Game ,C++/PYTHON实现,medium难度
- SWFUpload学习记录
- MacBook Pro 开机密码忘记的解决办法
- setjmp 及 alarm实现带超时限制调用read
- 如何使自己的QML应用不进入到屏保状态以保持屏幕是亮的
- Pro Android学习笔记(一六五):联系人API(8):控制整合
- LeetCode的medium题集合(C++实现)十三
- C++ 写leetcode遇到的一些问题总结string to integer
- Android Hook学习之ptrace函数的使用
- python爬虫第一课,制作搜索引擎
- Hiho 国庆出游
- Android应用Context详解及源码解析
- Uncaught TypeError: undefined is not a function
- 各种距离算法汇总
- 用c++实现 c++顺序表的实现(采用模板)