打卡第2天——977.有序数组的平方 209.长度最小的子数组 59.螺旋矩阵II

本文介绍了如何使用双指针法解决有序数组的平方问题,以及动态窗口法在找到满足条件子数组长度上的应用,还讨论了螺旋矩阵II的生成算法,涉及时间复杂度分析和常见错误总结。
摘要由CSDN通过智能技术生成

977.有序数组的平方

1.题目描述

力扣链接

2.适用场景 

暴力法:时间复杂度O(n + nlog n) 

双指针法:时间复杂度O(n)

3.做题思路

暴力法:先平方后直接排序

双指针法:创建新数组,对比两端大小,将大的平方放进新数组右端,返回值为新数组

b站讲解视频

4.代码实现

双指针法 

class Solution {
    public int[] sortedSquares(int[] nums) {
        int left=0;
        int right = nums.length - 1;
        int [] range = new int[nums.length];
        int index = range.length - 1;
        while (left<=right){
            if(nums[left]*nums[left] >=nums[right] * nums[right]){
                range[index]=nums[left] * nums[left];
                index--;
                left++;
            }
            else{
                range[index]=nums[right] * nums[right];
                index--;
                right--;
            }
        }
        return range;
    }
}

5.错误总结

 创建数组时错误认为,数组中[数字]为数组最后一个值的序号,正确:数组大小。

没有添加left=right的情况。

<=要连在一起写,长时间使用插件,代码格式忘了。

209.长度最小的子数组

1.题目描述

力扣链接

2.适用场景

 动态窗口法

  • 时间复杂度:O(n)

3.做题思路

 使两个指针像一个窗口右指针向前找到大于所给值时,左指针向前移

4.代码实现

 动态窗口法

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int sum = 0;
        int result = Integer.MAX_VALUE;
        int i = 0;
        for(int j = 0;j<nums.length;j++){
            sum += nums[j];
            while(sum>=target){
                result = Math.min(result,j-i+1);
                sum -=nums[i];
                i++;
            }
        }
       return result == Integer.MAX_VALUE ? 0 : result;
    }
}

5.错误总结 

使用Math函数时小写

写j<=nums.length数组越界

没有设置result为最大值,使所有返回值都为0;

59.螺旋矩阵II

1.题目描述

题目链接

2. 适用场景

时间复杂度 O(n^2): 模拟遍历二维矩阵的时间

3.做题思路

视频链接

不断遍历各个位置,奇数中心点直接赋值 

4.代码实现

class Solution {
    public int[][] generateMatrix(int n) {
        int [][]nums=new int [n][n];
        int startx = 0;
        int starty = 0;
        int loop =1;
        int off = 1;
        int i,j;
        int count =1;
        while(loop <= n/2){
            for(j=starty;j<n-off;j++){
                nums[startx][j] = count;
                count++;
            }
            for(i=startx;i<n-off;i++){
                nums[i][j]=count;
                count++;
            }
            for(;j>starty;j--){
                nums[i][j]=count;
                count++;
            }
            for(;i>startx;i--){
                nums[i][j]=count;
                count++;
            }
            startx++;
            starty++;
            off++;
            loop++;
        }
        if(n%2!=0){
            nums[startx][starty]=count;
        }
        return nums;
    }
}

5.错误总结

将初始y赋值为0导致错误

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值