记忆清晰呀,高德笔试题,可惜第一次还是提交失败,考虑不周到所致。就是在while里不能只判断横排或者竖排, 必须横竖都判断。
// LeetCode_MaximumSubarray.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int maxSubArray(int A[], int n) {
int curmax = A[0];
int max = curmax;
for (int i=1;i<n;i++)
{
if (curmax + A[i]>A[i])
curmax = curmax + A[i];
else
curmax = A[i];
if (curmax>max)
{
max = curmax;
}
}
return max;
}
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ret;
int lenrows = matrix.size();
if (lenrows==0)
{
return ret;
}
int lencolumns = matrix[0].size();
int left=0,up = 0,down = lenrows-1 , right= lencolumns-1;
int i,j;
while(left<=right&&up<=down)
{
i = up;
j = left;
while(i>=up&&i<=down&&j>=left&&j<=right)
{
ret.push_back(matrix[i][j]);
j++;
}
up++;
i = up;
j = right;
while(i>=up&&i<=down&&j>=left&&j<=right)
{
ret.push_back(matrix[i][j]);
i++;
}
right--;
i = down;
j =right;
while(i>=up&&i<=down&&j>=left&&j<=right)
{
ret.push_back(matrix[i][j]);
j--;
}
down--;
i = down;
j = left;
while(i>=up&&i<=down&&j>=left&&j<=right)
{
ret.push_back(matrix[i][j]);
i--;
}
left++;
}
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
//int arr[9]={-2,1,-3,4,-1,2,1,-5,4};
//cout<<maxSubArray(arr,9)<<endl;
vector<int> temp;
vector<vector<int> >matrix;
temp.push_back(1);
//matrix.push_back(temp);
//temp.clear();
/*temp.push_back(2);
temp.push_back(3);
temp.push_back(4);
temp.push_back(5);
temp.push_back(6);
matrix.push_back(temp);
temp.clear();
temp.push_back(7);
temp.push_back(8);*/
temp.push_back(9);
matrix.push_back(temp);
temp.clear();
//matrix.clear();
temp = spiralOrder(matrix);
for (int i=0;i<temp.size();i++)
{
cout<<temp[i]<<" ";
}
cout<<endl;
system("pause");
return 0;
}