代码随想录算法训练营第二天

有序数组的平方

双指针应用

题目:LeetCode.977

class Solution {
    public int[] sortedSquares(int[] nums) {
        int i = 0;
        int j = nums.length - 1;
        int[] arr = new int[nums.length];
        int k = arr.length - 1;
        while(i <= j){
            if(nums[i] * nums[i] >= nums[j] * nums[j]){
                arr[k--] = nums[i] * nums[i];
                i++;
            }
            else{
                arr[k--] = nums[j] * nums[j];
                j--;
            }
        }
        return arr;

    }
}

长度最小子数组

题目:LeetCode.209

写法1:暴力解法

写法2:滑动窗口

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

关键在于如何移动窗口的起始位置。

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

    }
}

螺旋矩阵

注意循环不变量

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] arr = new int[n][n];
        int cnt = 2;//循环次数
        int start = 0;//起始位置
        int val = 1;
        int i,j;
        while(cnt <= n){
            for(j = start ; j < n - cnt / 2 ; j++){
                arr[start][j] = val++;
            }
            for(i = start ; i < n - cnt / 2 ; i++){
                arr[i][j] = val++;
            }
            for(; j >= cnt / 2 ; j--){
                arr[i][j] = val++;
            }
            for(; i >= cnt / 2 ; i--){
                arr[i][j] = val++;
            }
            start++;
            cnt+=2;
        }
        if (n % 2 == 1) {
            arr[start][start] = val;
        }

        return arr;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值