算法训练营day2

Leetcode 977 有序数组的平方

题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/

//调用sort方法
class Solution {
    public int[] sortedSquares(int[] nums) {
        for(int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        Arrays.sort(nums);
        return nums;
    }
}
//双指针
class Solution {
    public int[] sortedSquares(int[] nums) {
        int len = nums.length;
        int[] ans = new int[len];
        int k = len - 1;
        for(int i = 0, j = len - 1; i <= j;) {
            if(nums[i] * nums[i] >= nums[j] * nums[j]) {
                ans[k--] = nums[i] * nums[i];
                i++;
            } else {
                ans[k--] = nums[j] * nums[j];
                j--;
            }
        }
        return ans;
    }
}

Leetcode 209 长度最小的子数组

题目链接:209. 长度最小的子数组 - 力扣(LeetCode)

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

Leetcode 59 螺旋矩阵II

题目链接:59. 螺旋矩阵 II - 力扣(LeetCode)

//偏移量法
class Solution {
    public int[] dx = {1,0,-1,0};
    public int[] dy = {0,-1,0,1};
    public int t  = 3;
    public int[][] generateMatrix(int n) {
        int[][] ans = new int[n][n];
        for(int i = 1, x = 0, y = 0; i <= n * n; i++) {
            ans[x][y] = i;
            int a = x + dx[t], b = y + dy[t];
            if(a < 0 || a >= n || b < 0 || b >= n || ans[a][b] != 0) {
                t = (t + 1) % 4;
                a = x + dx[t];
                b = y + dy[t];
            }
            x = a;
            y = b;
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值