代码随想录算法训练营第二天| 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵I

class Solution {
    public int[] sortedSquares(int[] nums) {
        // 双指针问题, 左边的指针指向原数组的最左边
        int left = 0;
        // 右边的指针, 指向原数组的最右边
        int right = nums.length - 1;
        // 计算之后, 从新数组最右边开始写
        int newIndex = nums.length - 1;
        int[] result = new int[nums.length];
        while (left <= right) {
            if (nums[left] * nums[left] > nums[right] *nums[right]) {
                result[newIndex] = nums[left] * nums[left];
                left++;
                newIndex--;
            } else {
                result[newIndex] = nums[right] *nums[right];
                right--;
                newIndex--;
            }
        }
        return result;
    }
}

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        // 滑动窗口, j是终止位置, i是起始位置, 从0开始
        int i = 0; 
        int result = Integer.MAX_VALUE;
        int sum = 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++];

            }
        }
        // 如果result仍为初始值,说明没有找到满足条件的子数组,返回0;否则返回result
        return result == Integer.MAX_VALUE ? 0 : result;

    }
}

class Solution {
    public int[][] generateMatrix(int n) {
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        int count = 1;
        int target = n*n;
        int[][] result = new int[n][n];
    
        while(count <= target) {
            // 从左到右填充,填充的列在[left,right]区间
            for (int i = left; i <= right; i++) {
                result[top][i] = count++; 
            }
            // 缩小上边界
            top++;
            // 从上到下填充, 填充的行在[top,bottom]区间
            for (int i = top; i <= bottom; i++) {
                result[i][right] = count++;
            }
            // 缩小右边界
            right--;
            // 从右向左填充, 填充的行在[top,bottom]区间
            for (int i = right; i >= left; i--) {
                result[bottom][i] = count++;
            }
            // 缩小下边界
            bottom--;
            //从下向上填充, 填充的行在[bootom,top]区间
            for(int i = bottom; i >= top; i--) {
                result[i][left] = count++;
            }
            // 缩小左边界
            left++;
        }
        return result;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值