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

复制代码
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;
    }
}
复制代码

 

posted @   坤坤无敌  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示