代码随想录-算法训练营day02【滑动窗口、螺旋矩阵】

  1. 专栏笔记:https://blog.csdn.net/weixin_44949135/category_10335122.html
https://docs.qq.com/doc/DUGRwWXNOVEpyaVpG?u=c71ed002e4554fee8c262b2a4a4935d8
 
977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结 

建议大家先独立做题,然后看视频讲解,然后看文章讲解,然后在重新做一遍题,把题目AC,最后整理成今日当天的博客

拓展题目可以先不做

 详细布置

 977.有序数组的平方 

题目建议: 本题关键在于理解双指针思想 

题目链接: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.长度最小的子数组

题目建议: 本题关键在于理解滑动窗口,这个滑动窗口看文字讲解 还挺难理解的,建议大家先看视频讲解。  拓展题目可以先不做。 

题目链接: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

题目建议:  本题关键还是在转圈的逻辑,在二分搜索中提到的区间定义,在这里又用上了。 

题目链接: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 

目录

0977_有序数组的平方【双指针】

0209_长度最小的子数组【滑动窗口】

0904_水果成篮

0076_最小覆盖子串

0059_螺旋矩阵2

0054_螺旋矩阵

LCR 146. 螺旋遍历二维数组


0977_有序数组的平方【双指针】

class Solution {
    public int[] sortedSquares(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            nums[i] = nums[i] * nums[i];
        }
        Arrays.sort(nums);
        return nums;
    }

    public int[] sortedSquares2(int[] nums) {//双指针法
        int left = 0, right = nums.length - 1, index = nums.length - 1;
        int res[] = new int[nums.length];
        while (left <= right) {
            if (Math.abs(nums[left]) > Math.abs(nums[right])) {
                res[index--] = nums[left] * nums[left];
                left++;
            } else {
                res[index--] = nums[right] * nums[right];
                right--;
            }
        }
        return res;
    }
}

0209_长度最小的子数组【滑动窗口】

class Solution {
    public int minSubArrayLen(int target, int[] nums) {//滑动窗口
        int sum = 0, index = 0, res = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            while (sum >= target) {
                //int len = i - index + 1;
                res = Math.min(res, i - index + 1);
                sum -= nums[index++];
            }
        }
        return res == -1 ? 0 : res;
    }

    public int minSubArrayLen2(int target, int[] nums) {//滑动窗口
        int result = Integer.MAX_VALUE;
        int sum = 0; // 滑动窗口数值之和
        int i = 0; // 滑动窗口起始位置
        int subLength = 0; // 滑动窗口的长度
        for (int j = 0; j < nums.length; j++) {
            sum += nums[j];
            //注意这里使用while,每次更新 i(起始位置),并不断比较子序列是否符合条件
            while (sum >= target) {
                subLength = (j - i + 1); // 取子序列的长度
                result = result < subLength ? result : subLength;
                sum -= nums[i++]; // 这里体现出滑动窗口的精髓之处,不断变更i(子序列的起始位置)
            }
        }
        //如果result没有被赋值的话,就返回0,说明没有符合条件的子序列
        return result == Integer.MAX_VALUE ? 0 : result;
    }

    public int minSubArrayLen3(int s, int[] nums) {//滑动窗口
        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++];
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}

0904_水果成篮

class Solution0904 {
    public int totalFruit(int[] fruits) {
        int n = fruits.length;
        Map<Integer, Integer> cnt = new HashMap<Integer, Integer>();//创建一个空的哈希表

        int left = 0, ans = 0;
        for (int right = 0; right < n; ++right) {
            //把水果加入哈希表中,你可以这么看cnt.put(水果类型,水果个数),key存储水果类型,而key对应的value存储对应的水果类型个数
            cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
            //当哈希表中的键值大于2时,也就是水果类型大于2时,进入while循环
            while (cnt.size() > 2) {
                //从哈希表中减去一个key==fruits[left]类型的水果,当key==fruits[left]这种类型的水果数等于0时,删除这种类型水果
                cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
                if (cnt.get(fruits[left]) == 0) {
                    cnt.remove(fruits[left]);
                }
                ++left;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}

0076_最小覆盖子串

class Solution {
    Map<Character, Integer> ori = new HashMap<Character, Integer>();
    Map<Character, Integer> cnt = new HashMap<Character, Integer>();

    public String minWindow(String s, String t) {
        int tLen = t.length();
        for (int i = 0; i < tLen; i++) {
            char c = t.charAt(i);
            ori.put(c, ori.getOrDefault(c, 0) + 1);
        }
        int l = 0, r = -1;
        int len = Integer.MAX_VALUE, ansL = -1, ansR = -1;
        int sLen = s.length();
        while (r < sLen) {
            ++r;
            if (r < sLen && ori.containsKey(s.charAt(r))) {
                cnt.put(s.charAt(r), cnt.getOrDefault(s.charAt(r), 0) + 1);
            }
            while (check() && l <= r) {
                if (r - l + 1 < len) {
                    len = r - l + 1;
                    ansL = l;
                    ansR = l + len;
                }
                if (ori.containsKey(s.charAt(l))) {
                    cnt.put(s.charAt(l), cnt.getOrDefault(s.charAt(l), 0) - 1);
                }
                ++l;
            }
        }
        return ansL == -1 ? "" : s.substring(ansL, ansR);
    }

    public boolean check() {
        Iterator iter = ori.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Character key = (Character) entry.getKey();
            Integer val = (Integer) entry.getValue();
            if (cnt.getOrDefault(key, 0) < val) {
                return false;
            }
        }
        return true;
    }
}

0059_螺旋矩阵2

class Solution0059 {
    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;
    }
}

0054_螺旋矩阵

class Solution0054 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        List<Integer> res = new ArrayList<>();
        int u = 0, d = m - 1, l = 0, r = n - 1;
        while (true) {
            for (int i = l; i <= r; i++) res.add(matrix[u][i]);
            if (++u > d) break;
            for (int i = u; i <= d; i++) res.add(matrix[i][r]);
            if (--r < l) break;
            for (int i = r; i >= l; i--) res.add(matrix[d][i]);
            if (--d < u) break;
            for (int i = d; i >= u; i--) res.add(matrix[i][l]);
            if (++l > r) break;
        }
        return res;
    }
}

LCR 146. 螺旋遍历二维数组

class Solution_LCR_0146 {
    public int[] spiralArray(int[][] array) {
        if (array == null || array.length == 0 || array[0].length == 0) {
            return new int[0];
        }
        int rows = array.length, columns = array[0].length;
        boolean[][] visited = new boolean[rows][columns];
        int total = rows * columns;
        int[] order = new int[total];
        int row = 0, column = 0;
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int directionIndex = 0;
        for (int i = 0; i < total; i++) {
            order[i] = array[row][column];
            visited[row][column] = true;
            int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
            if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
                directionIndex = (directionIndex + 1) % 4;
            }
            row += directions[directionIndex][0];
            column += directions[directionIndex][1];
        }
        return order;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/518600.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

(源码+部署+讲解)基于Spring Boot和Vue的大学生快递代取服务平台的设计与实现

一、引言 本报告旨在详细阐述基于Spring Boot后端框架和Vue前端框架的大学生快递代取服务平台的设计与实现过程。该平台旨在为大学生提供便捷的快递代取服务&#xff0c;解决因时间冲突或距离过远而无法及时取件的问题。通过该平台&#xff0c;用户可以发布代取需求&#xff0c…

[中级]软考_软件设计_计算机组成与体系结构_07_存储系统

存储系统 层次划存储概念图局促性原理分类存储器位置存取方式按内容存储按地址存储 工作方式拓展 往年真题 高速缓存(cache)概念案例解析&#xff1a;求取平均时间 Cache与主存的地址映射映像往年真题 主存编制计算编址大小的求取编址与计算存储单元编址内容总容量求取例题解析…

java爬虫入门程序

<!--爬虫仅支持1.8版本的jdk--> <!-- 爬虫需要的依赖--> <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version> </dependency><!-- 爬虫需…

github生成新的SSH密钥

首先是参考官方文档 生成新的 SSH 密钥并将其添加到 ssh-agent述 当你在创建SSH密钥时遇到提示&#xff1a; Enter file in which to save the key (/c/Users/YOU/.ssh/id_ALGORITHM):这一步是让你选择保存生成的SSH密钥对的文件名和位置。如果你直接按回车键&#xff08;[Pr…

Java项目:基于Springboot+vue实现的医院住院管理系统设计与实现(源码+数据库+开题报告+任务书+毕业论文)

一、项目简介 本项目是一套基于Springbootvue实现的医院住院管理系统设 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff0c;eclipse或者idea 确保可以运行&#xff01; 该系统功能完善、界面美观、操作简…

Activity入门2——生命周期与任务栈

OnCreate与OnDestroy OnCreate&#xff1a;创建一个活动。 OnDestroy&#xff1a;销毁一个活动。 假设某个用户在一个活动里输入了一些信息&#xff0c;用户由于某些原因退出了该活动&#xff0c;返回时希望能够还原之前输入的信息&#xff0c;不然重新输入就太麻烦了。 pub…

软考高级架构师:嵌入式软件开发概念和例题

一、AI 讲解 嵌入式软件开发和传统软件开发的差异 嵌入式软件开发与传统软件开发在目标、环境和开发过程等方面有显著的差异。下面通过对比的方式&#xff0c;简要阐述这些差异所在&#xff1a; 特性嵌入式软件开发传统软件开发开发目标针对特定硬件系统&#xff0c;强调软硬…

【Fn+windows键】‘Windows键+L’不能锁屏的问题

winL锁屏 3个键盘灯1.NumLock指示灯2.CapsLock指示灯3.ScrollLock指示灯 2.电脑锁屏问题 突然发现winL不能锁屏&#xff0c;反而是在自己打开的软件界面内编辑 各种操作之下&#xff0c;发现键盘上最不常用的灯亮了 所以了解了一番键盘灯的功能 3个键盘灯 1.NumLock指示灯 N…

快递费用一目了然:taobao.item_fee API在电商中的应用

taobao.item_fee API在电商中的应用主要体现在精准计算快递费用&#xff0c;从而为用户提供一个更加透明和便捷的购物体验。这一接口允许淘宝或天猫的开发者根据商品ID、收货地址等信息&#xff0c;精确计算商品的快递费用。对于用户而言&#xff0c;这意味着在购物过程中能够实…

工厂模式图

工厂模式 介绍一下简单工厂模式与工厂方法模式 结构图 简单工厂模式 工厂方法模式

【剑指offr--C/C++】JZ7 重建二叉树

一、题目 二、思路及代码 前序遍历&#xff1a;中、左、右。所以前序遍历的第一个节点是树的根节点&#xff0c;第二个节点是左子树的根节点。。。。 中序遍历&#xff1a;左、中、右。树的根节点在中间某处 我们可以根据二者的特点结合一下&#xff1a;对于前序遍历序列{1,2,4…

ubuntu安装sublime3并设置中文

安装Sublime Text 3 在Ubuntu上安装Sublime Text 3可以通过以下步骤进行&#xff1a; 打开终端。 导入Sublime Text 3的GPG密钥&#xff1a; wget -qO- https://download.sublimetext.com/sublimehq-pub.gpg | sudo apt-key add - 添加Sublime Text 3的存储库&#xff1a; …

纯C代码模板

一、快排 void QuickSort(int *a,int left,int right){if(left>right) return;else{int low left,high right;int pivot a[low];while(low<high){while(a[high] > pivot && low < high){high--;}a[low] a[high]; //必须先动a[low]while(a[low] < …

TR3 - Transformer算法详解

目录 文本输入处理词向量位置向量 编码器 EncoderSelf-Attention多头注意力机制残差连接 解码器 Decoder线性层与Softmax损失函数总结与心得体会 这周来看一下Transformer是怎么将文本转换成向量&#xff0c;然后又输入到模型处理并得到最终的输出的。 文本输入处理 词向量 …

计算机内存是如何管理的

计算内存的那些事儿——内存管理 大家回忆一下&#xff0c;计算机结构&#xff0c;或者说一个SoC&#xff08;system-on-chip&#xff09;芯片的结构。 cpu、memory、peripherals&#xff0c;这是计算机的主要部件&#xff0c;三者之间通过system bus勾搭在一起。 The main co…

易支付和独角数卡对接TokenPay开通USDT收款教程

TRX、USDT-TRC20、ETH系列区块链代币的支付通道是很多发卡和电商平台需要的&#xff0c;因为传统的微信、支付宝、PayPal等支付接口审查严格、手续费高。自建的代币接口完成没有手续费&#xff0c;稳定可靠&#xff0c;也没有审查要求。 易支付在行业普及广泛&#xff0c;大部…

JVM(Java虚拟机)

文章目录 一、JVM简介1.1 JVM概念1.2 什么是Java虚拟机呢&#xff1f;Java虚拟机的好处是什么呢&#xff1f; 二、JVM整体组成部分三、类加载器3.1 类加载子系统3.2 类加载过程3.2.1 装载(Load)3.2.2 链接(Link)3.2.3 初始化(Initialize) 四、运行时数据区4.1 方法区&#xff0…

stack 与 queue 与 priority_queue 与 仿函数 与 模板进阶

目录 stack queue deque priority_queue 使用 模拟实现 仿函数 仿函数的用法 仿函数的意义 模板进阶 非类型模板参数 模板特化 类模板特化的用法 类模板特化的意义 函数模板特化的用法 模板的分离编译 模板分离编译报错的原因 ​解决方法 模板总结 栈、队列…

Git安装教程(图文安装)

Git Bash是git(版本管理器)中提供的一个命令行工具&#xff0c;外观类似于Windows系统内置的cmd命令行工具。 可以将Git Bash看作是一个终端模拟器&#xff0c;它提供了类似于Linux和Unix系统下Bash Shell环境的功能。通过Git Bash&#xff0c;用户可以在Windows系统中运行基于…

【数据处理包Pandas】DataFrame对象的合并

目录 前言一、回顾Numpy数组的合并二、concat方法合并DataFrame对象三、append方法的使用四、merge方法合并DataFrame对象&#xff08;一&#xff09;比较merge与concat&#xff08;二&#xff09;参数on、left_on和right_on的用法&#xff08;三&#xff09;合并时四种不同的连…