第一章数组 (今日任务)
977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结
建议大家先独立做题,然后看视频讲解,然后看文章讲解,然后在重新做一遍题,把题目AC,最后整理成今日当天的博客
拓展题目可以先不做
详细布置
977.有序数组的平方
//方法1:直接排序
class Solution {
public int[] sortedSquares(int[] nums) {
int[] ans=new int[nums.length];
for(int i=0; i<nums.length; ++i){
ans[i]=nums[i]*nums[i];
}
Arrays.sort(ans);//必须大写A
return ans;
}
}
复杂度分析
时间复杂度:O(nlogn),其中 n是数组 nums 的长度。
空间复杂度:O(logn)。除了存储答案的数组以外,我们需要 O(logn) 的栈空间进行排序。
方法2:双指针
class Solution {
public int[] sortedSquares(int[] nums) {
int[] ans=new int[nums.length];
int k=nums.length-1;
int i=0,j=nums.length-1;
while(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;
}
}
这个题我一开始只写了k–而没不是ans[k–],所以运行的结果一直没成功排序,切记需要更新什么就写什么。
==题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/
文章讲解:https://programmercarl.com/0977.%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E7%9A%84%E5%B9%B3%E6%96%B9.html
视频讲解: https://www.bilibili.com/video/BV1QB4y1D7ep ==
209.长度最小的子数组
//滑动窗口
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int i=0; //起始值
int sum=0;
int k=Integer.MAX_VALUE;
for(int j=0;j<nums.length;j++){ //终值
sum += nums[j]; //叠加
while(sum >= target){ //叠加的值大于等于target才行动
k=Math.min(k,j-i+1); //个数总和 与 当前的k比较,取更小的个数和
sum=sum-nums[i]; //这里在缩小范围,为了取到长度最小的子数组,当前叠加的值减去左边不要的起始值
i++; //起始值往右移
}
}return k ==Integer.MAX_VALUE?0:k;
}
}
题目链接:https://leetcode.cn/problems/minimum-size-subarray-sum/
文章讲解:https://programmercarl.com/0209.%E9%95%BF%E5%BA%A6%E6%9C%80%E5%B0%8F%E7%9A%84%E5%AD%90%E6%95%B0%E7%BB%84.html
视频讲解:https://www.bilibili.com/video/BV1tZ4y1q7XE
59.螺旋矩阵II
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;
}
}
题目建议: 本题关键还是在转圈的逻辑,在二分搜索中提到的区间定义,在这里又用上了。
题目链接:https://leetcode.cn/problems/spiral-matrix-ii/
文章讲解:https://programmercarl.com/0059.%E8%9E%BA%E6%97%8B%E7%9F%A9%E9%98%B5II.html
视频讲解:https://www.bilibili.com/video/BV1SL4y1N7mV/
总结
题目建议:希望大家 也做一个自己 对数组专题的总结
文章链接:https://programmercarl.com/%E6%95%B0%E7%BB%84%E6%80%BB%E7%BB%93%E7%AF%87.html