209.长度最小的数组
使用滑动窗口,这个方法我是没有想到的
class Solution {
public:
int minSubArrayLen(int target, vector
int i = 0;
int min = nums.size()+1;
int j = 0;
int sum = 0;
for(;j < nums.size();++j)
{
sum += nums[j];
while(sum >= target)
{
if(min > j-i+1)
{
min = j-i+1;
}
sum -= nums[i++];
}
}
if(min == nums.size()+1)
{
return 0;
}
else
{
return min;
}
}
};
59.螺旋矩阵
使用有限状态机
class Solution {
public:
vector<vector
vector<vector
int x = 0;
int y = 0;
int state = 2;
int count = 0;
vector<vector
while(count < n * n)
{
switch(state)
{
case 1:
visited[y][x] = 1;
ret[y][x] = count + 1;
if(x == 0 || visited[y][x-1] == 1)
{
state = 3;
y--;
}
else
{
x--;
state = 1;
}
break;
case 2:
visited[y][x] = 1;
ret[y][x] = count + 1;
if(x == n-1 || visited[y][x+1] == 1)
{
state = 4;
y++;
}
else
{
x++;
state = 2;
}
break;
case 3:
visited[y][x] = 1;
ret[y][x] = count + 1;
if(y == 0 || visited[y-1][x] == 1)
{
state = 2;
x++;
}
else
{
y--;
state = 3;
}
break;
case 4:
visited[y][x] = 1;
ret[y][x] = count + 1;
if(y == n-1 || visited[y+1][x] == 1)
{
state = 1;
x--;
}
else
{
y++;
state = 4;
}
break;
}
count++;
}
return ret;
}
};
区间和
include
include
using namespace std;
int main()
{
int sum = 0;
int n;
cin >> n;
vector
vector
for(int i = 0; i < n; ++i)
{
cin >> vec1[i];
sum += vec1[i];
vec2[i] = sum;
}
int x1,x2;
while(cin >> x1 >> x2)
{
int m = 0;
if(x1 == 0)
{
m = vec2[x2];
}
else
{
m = vec2[x2] - vec2[x1-1];
}
cout << m << endl;
}
return 0;
}
开发商购买土地
这个我想了很久仍然没有想明白