算法学习day02数组part02-977、209、59

发布时间 2023-07-01 14:34:53作者: 坤坤无敌
package SecondBrush.Array;
/**
 * 977.有序数组的平方
 * 输入:nums = [-4,-1,0,3,10] 输出:[0,1,9,16,100]
 * <p>
 * 不看解题思路,想到的是双指针
 * 一个在开头,一个在末尾,但是一下没想到怎么写
 * 看了一下一刷内容,想到了,再定义一个变量来代表新数组的索引变化
 */
public class SquaresOfASortedArray_977 {
    public int[] sortedSquares(int[] nums) {
        int[] new_nums = new int[nums.length];
        int left = 0;
        int right = nums.length - 1;
        int index = nums.length - 1;
        while (left <= right) {
            if (nums[left] * nums[left] > nums[right] * nums[right]) {
                new_nums[index] = nums[left] * nums[left];
                index--;
                left++;
            } else {
                new_nums[index] = nums[right]*nums[right];
                index--;
                right--;
            }
        }
        return new_nums;
    }

}
package SecondBrush.Array;
/**
 * 209.长度最小的子数组
 * 前几天刚做过,现在突然看,还是想不起来怎么做的。只知道这个是使用双指针,类似于滑动窗口
 * 这个需要一个指标来动态更新最小长度
 * 想不起来,看答案梳理一下吧
 * 首先描述题目:一个数组,一个正整数,在数组找到一个连续数组和满足 >= s,且这个子数组长度最小,返回其长度
 * 双指针,先移动第二个指针,当sum>s时,则需要移动左指针向右,缩小sum,使其最小。定义一个变量来代表最小长度
 */

public class MinimumSizeSubarraySum_209 {
    public int minSubArrayLen(int[] nums, int s) {
        int left = 0;
        int sum = 0;
        int result = Integer.MAX_VALUE; // 因为返回最小长度,所以这里先取一个最大值占位
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum > s) {
                result = Math.min(result, right - left + 1);
                sum -= nums[left];
                left++;
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}
package SecondBrush.Array;

public class SpiralMatrixII_59 {
    public static int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int i = 0, j = 0, cur = 2;
        res[0][0] = 1;
        while (cur <= n * n) {
            while (j < n - 1 && res[i][j + 1] == 0) res[i][++j] = cur++; //
            while (i < n - 1 && res[i + 1][j] == 0) res[++i][j] = cur++; //
            while (j > 0 && res[i][j - 1] == 0) res[i][--j] = cur++; //
            while (i > 0 && res[i - 1][j] == 0) res[--i][j] = cur++; //
        }
        return res;
    }
}