代码随想录算法训练营第二天| 977. 有序数组的平方、209. 长度最小的子数组、59. 螺旋矩阵 II
977. 有序数组的平方
链接
理解左右指针
class Solution {
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
int left = 0;
int right = nums.length - 1;
int i = nums.length - 1;
while(left<=right){
if(nums[left]*nums[left]> nums[right]*nums[right]){
result[i] = nums[left]*nums[left];
left +=1;
}else{
result[i] = nums[right]*nums[right];
right -=1;
}
i -=1;
}
return result;
}
}
209. 长度最小的子数组
链接
理解滑动窗口,这题看似简单,用双重循环提交一直超时,看了答案才做出来。
滑动窗口:左指针、右指针一直前移不后退。右指针先右移,左指针左移,求满足要求的值,记录下最小值。
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int end = 0;
int sum = 0;
int start = 0;
int minLength = Integer.MAX_VALUE;
while(end<=nums.length-1){
sum = sum+nums[end];
while(sum>=target){
minLength = Math.min(minLength, end-start+1);
sum -=nums[start];
start++;
}
end++;
}
return minLength==Integer.MAX_VALUE?0:minLength;
}
}
59. 螺旋矩阵 II
class Solution {
public int a;
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int num = 1;
int top = 0,bottom = n-1,left=0,right=n-1;
while(left<=right&&top<=bottom){
for(int i = left;i<=right-1;i++){
res[top][i]=num;
num ++;
}
for(int i = top;i<=bottom-1;i++){
res[i][right]=num;
num ++;
}
for(int i = right;i>=left+1;i--){
res[bottom][i]=num;
num ++;
}
for(int i = bottom;i>=top+1;i--){
res[i][left]=num;
num ++;
}
left++;
right--;
top++;
bottom--;
}
if(n%2==1){
res[n/2][n/2]=n*n;
}
return res;
}
}