代码随想录Day2 | 977.有序数组的平方、209.长度最小的子数组、59.螺旋矩阵II | 双指针、滑动窗口、二维数组

860 阅读1分钟

977.有序数组的平方

题目链接:977. 有序数组的平方 - 力扣(LeetCode)

思路: 这题还是比较熟悉的,题目已经明确了是非递减排序的数组,那么左右双指针一头一尾进行扫描,将平方值较大的那个放到数组的末尾即可。

Code

class Solution {
    public int[] sortedSquares(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        int left = 0, right = n - 1;
        int index = n - 1;
        while (index >= 0) {
            if (nums[left] * nums[left] >= nums[right] * nums[right]) {
                res[index--] = nums[left] * nums[left];
                left++;
            } else {
                res[index--] = nums[right] * nums[right];
                right--;
            }
        }
        return res;
    }

209.长度最小的子数组

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

思路: 刚开始想用前缀和做,因为最近在看这个,但是想了一会儿感觉有点麻烦。还是用滑动窗口做了。第一遍写的时候res的初始值没有设置成Integer.MAX_VALUE。

Code

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

59.螺旋矩阵II

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

思路: 这道题直接做过,有印象,但是写循环内部的时候想了半天还是没思路。。。

Code

class Solution {
    public int[][] generateMatrix(int n) {
        int loop = 0;  // 控制循环次数
        int[][] res = new int[n][n];
        int start = 0;  // 每次循环的开始点(start, start)
        int count = 1;  // 定义填充数字
        int i, j;

        while (loop++ < n / 2) { // 判断边界后,loop从1开始
            // 模拟上侧从左到右
            for (j = start; j < n - loop; j++) {
                res[start][j] = count++;
            }

            // 模拟右侧从上到下
            for (i = start; i < n - loop; i++) {
                res[i][j] = count++;
            }

            // 模拟下侧从右到左
            for (; j >= loop; j--) {
                res[i][j] = count++;
            }

            // 模拟左侧从下到上
            for (; i >= loop; i--) {
                res[i][j] = count++;
            }
            start++;
        }

        if (n % 2 == 1) {
            res[start][start] = count;
        }

        return res;
    }
}

总结: 按照右、下、左、上的顺序遍历数组,坚持每条边左闭右开的原则。