算法记录|Day02

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 长度最小的子数组

滑动窗口就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。

1.只用一个for循环
确定终点的位置
2.通过条件更新起点
记录最小或者最大的起点位置
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;
    }
}

总结

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值