10.《滑动窗口篇》---②长度最小的子数组(中等)

有了上一篇的基础。这道题我们就可以轻易分析可以使用滑动窗口来解决了

方法一:滑动窗口

这里注意 ret 在while循环外部更新

while 外部更新 ret,确保窗口在满足条件后再计算长度,避免错误计入正在调整中的窗口长度。

java 复制代码
class Solution {
    public int lengthOfLongestSubstring(String s0) {
        int[] hash = new int[128]; //数组模拟哈希表
        int n = s0.length();
        char[] s = s0.toCharArray();
        int ret = 0;

        for(int left = 0,right = 0; right < n; right++){
            hash[s[right]]++; //进入窗口
            while(hash[s[right]] > 1){
                hash[s[left++]]--;
            }
            ret = Math.max(ret,right-left+1);
        }
        return ret;
    }
}

复杂度分析

时间复杂度:O(n),

空间复杂度:

  • 常见分析: 空间复杂度为 O(1),因为哈希表是固定大小,额外空间使用与输入大小无关。
  • 严格分析 : 如果字符数组 chars 被视为额外空间,则空间复杂度为 O(n)
相关推荐
‎ദ്ദിᵔ.˛.ᵔ₎7 分钟前
滑动窗口算法
算法·哈希算法
Fly Wine27 分钟前
Leetcode只二叉树中序遍历(python解法)
算法·leetcode·职场和发展
倦王14 小时前
力扣日刷47-补
python·算法·leetcode
无限进步_16 小时前
【C++】巧用静态变量与构造函数:一种非常规的求和实现
开发语言·c++·git·算法·leetcode·github·visual studio
凌波粒16 小时前
LeetCode--344.反转字符串(字符串/双指针法)
算法·leetcode·职场和发展
啊哦呃咦唔鱼16 小时前
LeetCode hot100-543 二叉树的直径
算法·leetcode·职场和发展
样例过了就是过了17 小时前
LeetCode热题100 爬楼梯
c++·算法·leetcode·动态规划
ThisIsMirror18 小时前
leetcode 452 Arrays.sort()排序整数溢出、Integer.compare(a[1], b[1])成功的问题
算法·leetcode
x_xbx19 小时前
LeetCode:438. 找到字符串中所有字母异位词
算法·leetcode·职场和发展
派大星~课堂19 小时前
【力扣-94.二叉树的中序遍历】Python笔记
笔记·python·leetcode