977.有序数组的平方
看到题目的第一想法:
这道题也是做过很多遍的了,标准的双指针法,但用暴力也还是很方便,主要还是对于逆向思维的考察,在填充数组的时候注意要从后往前,这样保证负数在平方后直接到自己想要的位置
class Solution { public: vector<int> sortedSquares(vector<int>& nums) { //暴力解法 for(int i = 0; i < nums.size(); i++) { nums[i] = nums[i] * nums[i]; } sort(nums.begin(), nums.end()); return nums; } };
class Solution { public: vector<int> sortedSquares(vector<int>& nums) { // 双指针原地解法 vector<int> res(nums.size()); int len = nums.size() - 1; int left = 0; int right = nums.size() - 1; // 当left和right相等的时候满足条件 while(left <= right) { if(nums[left]*nums[left] > nums[right] * nums[right]) { res[len--] = nums[left] * nums[left]; left++; } else { res[len--] = nums[right] * nums[right]; right--; } } return res; } };
遇到的困难:
这道题还算顺利
209.长度最小的子数组
看到题目的第一想法:
这道题一开始是用while循环,后来发现在最后一个数一直有边界问题,解决好久都不能很好解决,后来还算使用了for循环轻轻松松解决,这也看出来for和while循环选择的重要性
class Solution { public: int minSubArrayLen(int target, vector<int>& nums) { // 双指针法,滑动窗口解法 int j = 0; int sum = 0; int res = INT_MAX; for(int i = 0; i < nums.size(); i++) { sum += nums[i]; while(sum >= target) { res = res > (i - j + 1) ? (i - j + 1) : res; sum -= nums[j++]; } } return res == INT_MAX ? 0 : res; } };
遇到的问题:
for和while循环的选择,这里面也考察了对于滑动窗口的复习,很好的一道题
59.螺旋矩阵II
看到题目的第一想法:
这道题虽然做过很多遍,但看第一眼还是很难直接有思路,只能在本子上去画出自己的想法,一步步根据自己的想法来,定义变量的时候也不能很好的直接定义完整,只能说缺什么补什么,对于左闭右开,循环不变量是很好的体现,要从头到底实现左闭右开。
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n,vector<int>(n,0)); // 圈数 int loop = n/2; // 需要赋值的数 int count = 1; // 每圈打印的个数 int num_1 = 1; // 定义起始下标 int x_ = 0; int y_ = 0; while(loop) { int x = x_; int y = y_; for(; y < n - num_1; y++) { res[x][y] = count++; } for(; x < n - num_1; x++) { res[x][y] = count++; } for(; y > y_; y--) { res[x][y] = count++; } for(; x > x_; x--) { res[x][y] = count++; } x_++; y_++; loop--; num_1++; } if(n%2 == 1) { res[n/2][n/2] = count; } return res; } };
遇到的问题:
这道题在每次左闭右开的时候打印的个数上出现了小问题,一开始是用起始点相加的方式,后来发现这样很容易溢出,然后使用carl哥的方法,使用最大圈数来减这样就好理解了许多
数组总结
数组这一章耗时2天完结,这次也是比较顺利的做出了这些题,主要是做了太多遍了,之前都断断续续做,从来没有好好把代码随想录刷一遍,趁着这次训练营好好的做一次,加油!!!为明年四月份的蓝桥杯加油!!!