day02|977.有序数组的平方,209.长度最小的子数组,59.螺旋矩阵II

977.有序数组的平方

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

思路

  1. 暴力解法,全部平方后Array.sort()。时间复杂度O(nlog n)
  2. 左右双指针。情况一:没有负数,数组元素小—>大;情况二:没有正数,数组元素大—>小;情况三:有正有负,数组元素大—>小—>大。情况一和情况二都是情况三的特殊情况,只有一个指针在移动。时间复杂度O(n)

代码

//两边向中间移动
class Solution {
    public int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        if (nums[0] >= 0) {
            for (int i = 0; i < n; i++) {
                res[i] = nums[i] * nums[i];
            }
            return res;
        }
        int left = 0, right = n - 1;
        int lastIndex = n - 1;
        while (left <= right) {
            if (nums[left] * nums[left] > nums[right] * nums[right]) {
                res[lastIndex--] = nums[left] * nums[left];
                left++;
            } else {
                res[lastIndex--] = nums[right] * nums[right];
                right--;
            }
        }
        return res;
    }
}

209.长度最小的子数组

题目链接:https://leetcode.cn/problems/minimum-size-subarray-sum/

思路

采用滑动窗口,注意何时窗口要扩大,何时要缩小。时间复杂度O(n)

代码

class Solution {
    public int minSubArrayLen(int target, int[] nums) {
        int sum = 0;//窗口内的值
        int left = 0;
        int minLen = nums.length + 1;
        for (int right = 0; right < nums.length; right++) {
        	//窗口扩大,rigth移动
            sum += nums[right];
            while (sum >= target) {
                //窗口缩小,更新长度,left移动
                minLen = Math.min(right - left + 1, minLen);
                sum -= nums[left++];
            }
        }
        return minLen == nums.length + 1 ? 0 : minLen;
    }
}

59.螺旋矩阵II

题目链接:https://leetcode.cn/problems/spiral-matrix-ii/

思路

按照示例图一步一步来就行了

代码

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int top = 0, bottom = n - 1, left = 0, right = n - 1;
        int curNumber = 1;
        while (curNumber <= n * n) {
            for (int i = left; i <= right; i++) {
                res[top][i] = curNumber++;
            }
            top++;

            for (int i = top; i <= bottom; i++) {
                res[i][right] = curNumber++;
            }
            right--;

            for (int i = right; i >= left; i--) {
                res[bottom][i] = curNumber++;
            }
            bottom--;

            for (int i = bottom; i >= top; i--) {
                res[i][left] = curNumber++;
            }
            left++;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值