209.长度最小的子数组
思路:滑动窗口经典题目,外层for,遍历数组移动滑动窗口右边界,内层while,在满足题目条件的情况下,移动滑动窗口左边界。虽然看似有两层循环,但是每个元素最多一进一出两次操作,所以复杂度是2n。
题解:
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int ret{INT_MAX}, sum{0}, i{0};
for (int j = 0; j < nums.size(); j++)
{
sum += nums[j];
while (sum >= target)
{
int sublen = j - i + 1;
ret = ret < sublen ? ret : sublen;
sum -= nums[i];
++i;
}
}
return ret == INT_MAX ? 0 : ret;
}
};
59. 螺旋矩阵 II
思路:这种题纯考细心,以前我虽然能写,但是花的时间比较久,感觉还是思路不清晰。后面看见了别人的答案,设置了l,r,t,b四个变量来操作后一下子清晰了许多,所有关于这种矩阵输出的问题我建议都这样处理,代码会舒服很多且过程一目了然。
题解:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int l{0}, t{0}, r{n-1}, b{n-1}, loop{n/2 + 1}, count{0};
vector<vector<int>> ret(n, vector<int>(n));
while (loop)
{
for (int i = l; i <= r; ++i)
ret[t][i] = ++count;
++t;
for (int i = t; i <= b; ++i)
ret[i][r] = ++count;
--r;
for (int i = r; i >= l; --i)
ret[b][i] = ++count;
--b;
for (int i = b; i >= t; --i)
ret[i][l] = ++count;
++l;
--loop;
}
return ret;
}
};
区间和
题目链接:区间和
思路:一眼暴力,然后超时了,寄,看讲解去了。
讲解:区间和
其实就是多用了一个数组预先储存好前缀和,降低了累加时的时间复杂度。但是我还是超时了,看了一下解答,发现要用scanf代替cin,才能满足时限。
题解:
暴力法
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n{0},a{0}, b{0};
cin>>n;
vector<int>nums(n);
for (int i{0}; i < n; ++i)
cin >> nums[i];
while (cin >> a >>b)
{
int sum{0};
for (int i{a}; i<=b; ++i)
sum += nums[i];
cout << sum << endl;
}
}
前缀和:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n{0},a{0}, b{0};
scanf("%d", &n);
vector<int>nums(n);
vector<int>pre(n);
int presum{0};
for (int i{0}; i < n; ++i)
{
scanf("%d", &nums[i]);
presum += nums[i];
pre[i] = presum;
}
while (~scanf("%d%d", &a, &b))
{
int sum = a != 0 ? pre[b] - pre[a-1] : pre[b];
printf("%d\n", sum);
}
}
开发商购买土地
题目链接:开发商购买土地
思路:做了上一题,想到应该是横向纵向分别生成一个储存前缀和的vector,后面再在这两个vector上遍历一遍就行。感觉以后遇见区间求和的问题,应该都要考虑一下前缀和的方法,还有这种要自己写输入输出的题,别老忘了写int main了。。。
题解:
题解:
暴力法
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
int main()
{
int n{0}, m{0};
scanf("%d%d", &n, &m);
vector<vector<int>> Mat(n, vector<int>(m));
for (int i{0}; i < n; ++i)
{
for (int j{0}; j < m; ++j)
{
scanf("%d", &Mat[i][j]);
}
}
vector<int> hor(m);
int hor_sum{0};
for (int i{0}; i < m; ++i)
{
for (int j{0}; j < n; ++j)
hor_sum += Mat[j][i];
hor[i] = hor_sum;
}
vector<int> ver(n);
int ver_sum{0};
for (int i{0}; i < n; ++i)
{
for (int j{0}; j < m; ++j)
ver_sum += Mat[i][j];
ver[i] = ver_sum;
}
int diff{INT_MAX};
int ret{INT_MAX};
for (int i{0}; i < m - 1; ++i)
{
diff = 2*hor[i] - hor[m-1];
diff = diff > 0 ? diff : -diff;
ret = ret < diff ? ret : diff;
}
for (int i{0}; i < n - 1; ++i)
{
diff = 2*ver[i] - ver[n-1];
diff = diff > 0 ? diff : -diff;
ret = ret < diff ? ret : diff;
}
printf("%d", ret);
}