代码随想录训练营第二天 |977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II
今天是训练营第二天,包含了第一天双指针的扩展题
class Solution { public int[] sortedSquares(int[] nums) { int n = nums.length; int[] res = new int[n]; int l = 0; int r = n-1; int i = r; while(l <= r){ if(nums[l]*nums[l] < nums[r]*nums[r]){ res[i--] = nums[r]*nums[r]; r--; } else{ res[i--] = nums[l]*nums[l]; l++; } } return res; } }
这道题要注意的点就是负数的平方为正数,因此我们从最大的值开始处理就可以了。
class Solution { public int minSubArrayLen(int target, int[] nums) { int n = nums.length; int res = Integer.MAX_VALUE; int l = 0; int sum = 0; for(int i = 0; i<n; i++){ sum += nums[i]; while(sum >= target){ res = Math.min(res, i - l + 1); sum -= nums[l]; l ++; } } return res == Integer.MAX_VALUE ? 0 : res; } }
滑动窗口基本题,不断向左扩大窗口,如果窗口中的值超过了target,再缩小窗口右边直至窗口中的值小于等于target,再往复进行。
class Solution { public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int row = 0; int col = 0; int count = 1; boolean notEnd = true; while(notEnd){ notEnd = false; while(col < n && res[row][col]==0){ res[row][col]= count; count ++; col ++; } col--; row++; while(row < n && res[row][col]==0 ){ res[row][col]= count; count ++; row ++; } col--; row--; while(col >= 0 && res[row][col]==0){ res[row][col]= count; count ++; col --; } col++; row--; while(row >= 0 &&res[row][col]==0){ res[row][col]= count; count ++; row --; notEnd = true; } row++; col++; } return res; } }
看了题解的方法。 按照四边顺序填充,如果遇到有之前填过的(非0的),就换边
今天第二天的训练题目,难度明显比第一天高出不少。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?