class Solution {
public:
vector<int> printMatrix(vector<vector<int> > mat) {
vector<int> output;
int cb = 0, ce = mat[0].size()-1, rb = 0, re = mat.size()-1,step = -1,
r,c, elementNumber = mat[0].size() * mat.size();
while( output.size() < elementNumber){
step *= -1;
for(r = rb, c = cb; c != ce + step; c += step)
output.emplace_back(mat[r][c]);
rb += step;
for(c = ce,r = rb; r != re + step; r += step)
output.emplace_back(mat[r][c]);
ce -= step;
swap(rb,re);
swap(cb,ce);
}
return output;
}
};改成迭代器实现快 1ms
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > mat) {
vector<int> output;
vector<vector<int> >::iterator r;
int rb = 0, re = mat.size()-1, cb = 0, ce = mat[0].size()-1;
vector<int>::iterator c;
int step = -1, elementNumber = mat[0].size() * mat.size();
while(output.size() < elementNumber){
step *= -1;
for(r = mat.begin()+rb, c = (*r).begin() + cb;
c != (*r).beg***ep; c += step)
output.emplace_back(*c);
rb += step;
for(r = mat.begin()+rb; r != mat.begin() + re + step; r += step)
output.emplace_back( *((*r).begin()+ce) );
ce -= step;
swap(rb,re);
swap(cb,ce);
}
return output;
}
};
京公网安备 11010502036488号