今天的这三道题每道题对我来说都不简单,有序数组的平方和长度最小的子数组这两道题还能用暴力求解,螺旋矩阵看着简单却没有思路,磨了半小时还是决定直接看讲解
有序数组平方和用的双指针的思想,代码如下:
1 class Solution { 2 public: 3 vector<int> sortedSquares(vector<int>& nums) { 4 int n = nums.size(); 5 vector<int> A(n); 6 int head,tail,a,b; 7 head =0; 8 tail = n-1; 9 int p = n-1; 10 while(head<=tail){ 11 a = nums[head]*nums[head]; 12 b = nums[tail]*nums[tail]; 13 if(a<b){ 14 A[p]=b; 15 tail--; 16 p--; 17 }else{ 18 A[p]=a; 19 head++; 20 p--; 21 } 22 } 23 return A; 24 } 25 };
长度最小子数组使用滑动窗口的思想:
1 class Solution { 2 public: 3 int minSubArrayLen(int target, vector<int>& nums) { 4 int result = INT32_MAX; 5 int len=0; 6 int sum =0; 7 int j=0; 8 for(int i=0;i<nums.size();i++){ 9 sum +=nums[i]; 10 while(sum>=target){ 11 len = i-j+1; 12 result = result<len?result:len; 13 sum-=nums[j]; 14 j++; 15 } 16 17 } 18 return result==INT32_MAX?0:result; 19 } 20 };
螺旋矩阵的思想是按从左到右、从上到下、从右到左、从下到上这个循环来赋值
1 class Solution { 2 public: 3 vector<vector<int>> generateMatrix(int n) { 4 vector<vector<int>> res(n,vector<int>(n,0)); 5 int startx=0,starty=0; 6 int loop = n/2; 7 int mid = n/2; 8 int i=0,j=0; 9 int offset=1; 10 int count = 1; 11 while(loop>0){ 12 i=starty; 13 j=startx; 14 for(j=startx;j<n-offset;j++) 15 res[i][j]=count++; 16 for(i=starty;i<n-offset;i++) 17 res[i][j]=count++; 18 for(;j>offset-1;j--) 19 res[i][j]=count++; 20 for(;i>offset-1;i--) 21 res[i][j]=count++; 22 loop--; 23 offset+=1; 24 startx++; 25 starty++; 26 } 27 if(n%2==1) 28 res[mid][mid]=n*n; 29 return res; 30 } 31 };
标签:977,startx,int,res,随想录,++,vector,数组 From: https://www.cnblogs.com/yangboran/p/17655402.html