剑指offer:顺时针打印矩阵

这道题为什么我在本地写了很多测试数据,均通过了,但是放到牛客网上测试, 运行超时?
我自认为这个算法比较简单,应该不会超时啊。。。
我的代码,顺便放上了自己写的测试,可以简单修改,就在主函数里面:

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
vector<int> printMatrix(vector<vector<int>> matrix) {
vector <int> res;
int rows = matrix.size();
int cols = matrix[0].size();
int cnt = rows * cols;
int left = 0, top = 0;
int bottom = rows - 1;
int right = cols - 1;
while (true) {
for (int i = left; i < right; ++i) {
res.push_back(matrix[top][i]);
--cnt;
if (0 >= cnt) return res;
}
for (int i = top; i < bottom; ++i) {
res.push_back(matrix[i][right]);
--cnt;
if (0 >= cnt) return res;
}
for (int i = right; i > 0; --i) {
res.push_back(matrix[bottom][i]);
--cnt;
if (0 >= cnt) return res;
}
for (int i = bottom; i > 0; --i) {
res.push_back(matrix[i][left]);
--cnt;
if (0 >= cnt) return res;
}
++left;
--right;
++top;
--bottom;
}
}
};

int main () {
int row = 3;
int col = 4;
auto solve = new Solution();
vector <vector <int>> v(row);
for (int i = 0; i < row; ++i) v[i].resize(col);
int cnt = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
v[i][j] = ++cnt;
}
}
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
cout << v[i][j] << "\t";
}
cout << endl;
}
cout << endl;
vector <int> res = solve -> printMatrix(v);
for (int i = 0; i < res.size(); ++i) {
cout << res[i] << endl;
}
return 0;
}




#笔试题目##C/C++##题解#
全部评论
https://blog.csdn.net/qq_38635597/article/details/89257239  整理左神讲的,简单易懂
点赞 回复
分享
发布于 2019-05-11 19:59

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务