Day02 第一章数组


一、977.有序数组的平方

1.原题

class Solution {
    public int[] sortedSquares(int[] nums) {

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

此题的关键就是双向指针,一个从前往后一个从后往前,无其他难度。

二、 209.长度最小的子数组

1.原题

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

此题的思路还是使用两个指针,与快慢指针类似,一在前一个在后,首先把前几个数组相加,直到满足条件,然后记录此子数组的大小,然后去掉最右边一个元素,再次判断是否满足条件,循环往复,直到找到复合条件的为止。

三、59.螺旋矩阵II

1.原题

class Solution {
    public int[][] generateMatrix(int n) {
        int loop = 0;
        int start = 0;
        int num = 1;
        int j,i;
        int[][] arr = new int[n][n];
        while (n / 2 > loop++){

            for(j = start; j < n - loop; j++){
                arr[start][j] = num++;
            }
            for(i = start;i < n - loop; i++){
                arr[i][j] = num++;
            }
            for(;j > start; j--){
                arr[i][j] = num++;
            }
            for(;i > start; i--){
                arr[i][j] = num++;
            }
            start++;
        }
        if(n % 2 == 1){
            arr[start][start] = num;
        }
        return arr;
    }
}

这里最难处理的是边界问题和循环次数问题
边界问题:边界处理可能会出现重复,所以要再一开始就确认好边界,每次都不包括本次循环的最后一个值
循环次数问题:每次循环都会减少两条边,所以n/2的值为循环次数,如果为奇数,最后单独为最中间的值进行赋值操作。
思路:先考虑最外层循环如何进行,最外层循环结束后,对内层进行参数控制即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值