Leecode题目
Leecode 977 有序数组的平方
双指针法:
- i i i指向起始位置, j j j指向终止位置。
- 单独定义一个结果数组,k指向result数组终止位置。
- 终止条件:原数组各个元素被遍历(i<=j)
class Solution {
public int[] sortedSquares(int[] a) {
int i =0;
int j = a.length-1;
int k =j;
int[] res = new int[a.length];
while(i<=j){
if(a[i]*a[i]>a[j]*a[j]){
res[k--] =a[i]*a[i++] ;
}else{
res[k--] =a[j]*a[j--] ;
}
}
return res;
}
}
Leecode 209 长度最小的子数组
滑动窗口:就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。
class Solution {
public int minSubArrayLen(int target, int[] a) {
int i =0;
int result = Integer.MAX_VALUE;
int sublength =0;
int sum =0;
for(int j=0;j<a.length;j++){
sum += a[j];
while(sum>=target){
sublength = (j-i+1);
result = result<sublength?result:sublength;
sum -=a[i++];
}
}
return result == Integer.MAX_VALUE?0:result;
}
}
重点:中间是while循环。
Leecode 59 螺旋矩阵II
模拟顺时针画矩阵的过程:
- 填充上行从左到右 。在 t o p top top行, l e f t < = i < = r i g h t left<=i <=right left<=i<=right, n u m s [ t o p ] [ i ] nums[top][i] nums[top][i]
- 填充右列从上到下。在 r i g h t right right列, t o p < = i < = b o t t o m top<=i <=bottom top<=i<=bottom, n u m s [ i ] [ r i g h t ] nums[i][right] nums[i][right]
- 填充下行从右到左。在 b o t t o m bottom bottom行, r i g h t > = i = > l e f t right>=i =>left right>=i=>left, n u m s [ b o t t o m ] [ i ] nums[bottom][i] nums[bottom][i]
- 填充左列从下到上。在 l e f t left left列, b o t t o m > = i = > t o p bottom>=i =>top bottom>=i=>top, n u m s [ i ] [ l e f t ] nums[i][left] nums[i][left]
由外向内一圈一圈这么画下去。
注意:
每填充完一行或者一列,需要更新当前行或者列的大小。
class Solution {
public int[][] generateMatrix(int n) {
int top = 0, left = 0, right = n-1,bottom = n-1;
int count = 1, target = n*n;
int[][] res = new int [n][n];
while(count<=target){
//左到右
for(int i = left;i<=right;i++){
res[top][i] = count++;
}
top++;
//上到下
for(int i = top;i<=bottom;i++){
res[i][right] = count++;
}
right--;
//右到左
for(int i = right;i>=left;i--){
res[bottom][i] = count++;
}
bottom--;
//下到上
for(int i = bottom;i>=top;i--){
res[i][left] = count++;
}
left++;
}
return res;
}
}