题目:
1. Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
【解题思路】
顺着spiralorder剥皮,up->right->bottom->left. 用四个变量x1, x2, y1, y2 控制上下左右边界。注意循环条件为x1<=x2 && y1<= y2
另外注意每行和每列输出的范围
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> result;
if(matrix.size() == 0) return result;
int x1 = 0;
int y1 = 0;
int x2 = matrix.size() - 1;
int y2 = matrix[0].size() - 1;
while(x1<=x2 && y1<=y2){
//up row
for(int j = y1; j<=y2; ++j){
result.push_back(matrix[x1][j]);
}
// right column
for(int i = x1+1; i<=x2; ++i){
result.push_back(matrix[i][y2]);
}
if(x2 !=x1){
// bottom row
for(int j = y2-1; j>=y1; --j){
result.push_back(matrix[x2][j]);
}}
if(y2 != y1){
// left column
for(int i = x2-1; i>x1; --i){
result.push_back(matrix[i][y1]);
}}
x1++, y1++, x2--, y2--;
}
return result;
}
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
【解题思路】
和第一题类似,反过来构造就可以了。Code可以复用
vector<vector<int> > generateMatrix(int n) {
vector<vector<int>> matrix(n);
if(n == 0) return matrix;
for(int i=0; i<n; i++){
matrix[i].resize(n);
}
int x1 = 0;
int y1 = 0;
int x2 = n - 1;
int y2 = n - 1;
int val = 1;
while(x1<=x2 && y1<=y2){
//up row
for(int j = y1; j<=y2; ++j){
matrix[x1][j] = val++;
}
// right column
for(int i = x1+1; i<=x2; ++i){
matrix[i][y2] = val++;
}
if(x2 !=x1){
// bottom row
for(int j = y2-1; j>=y1; --j){
matrix[x2][j] = val++;
}}
if(y2 != y1){
// left column
for(int i = x2-1; i>x1; --i){
matrix[i][y1] = val++;
}}
x1++, y1++, x2--, y2--;
}
return matrix;
}
3. Set matrix zeros
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
如果矩阵中某一元素为零,则将其所在列与行置为零
click to show follow up.
需要对算法进行优化的点
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?
【解题思路】
解题点就在于清空标志位存在哪里。可以创建O(m+n)的数组来存储,选择第一行和第一列来存储标志位。
1.先确定第一行和第一列是否需要清零
2.扫描剩下的矩阵元素,如果遇到了0,就将对应的第一行和第一列上的元素赋值为0
3.根据第一行和第一列的信息,已经可以讲剩下的矩阵元素赋值为结果所需的值了
4.根据1中确定的状态,处理第一行和第一列。
void setZeroes(vector<vector<int> > &matrix) {
assert(matrix.size() >0);
int row = matrix.size();
int column = matrix[0].size();
bool zeroRow = false, zeroCol = false;
for(int i=0; i<column; i++){
if(matrix[0][i] == 0)
zeroRow = true;
}
for(int i=0; i<row; i++){
if(matrix[i][0] == 0)
zeroCol = true;
}
for(int i=1; i<row; i++){
for(int j=1; j<column; j++){
if(matrix[i][j]==0){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for(int i=1; i<row; i++){
for(int j=1; j<column; j++){
if(matrix[i][0]==0 || matrix[0][j]==0)
matrix[i][j] = 0;
}
}
if(zeroRow == true){
for(int i=0; i<column;i++){
matrix[0][i] = 0;
}
}
if(zeroCol == true){
for(int i=0; i<row;i++){
matrix[i][0] = 0;
}
}
}
未完,待续...