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)
相关推荐
Tim_1031 分钟前
【LeetCode】338、比特位计数
c++·算法·leetcode
mmmmath_32 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z2 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.2 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好3 小时前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法
All for pursuit.3 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
圣保罗的大教堂3 小时前
leetcode 1665. 完成所有任务的最少初始能量 中等
leetcode
Tisfy18 小时前
LeetCode 3498.字符串的反转度:一次遍历
leetcode·字符串·题解·遍历
a1879272183118 小时前
【算法】树(二):队列与祖先——BFS 骨架三配件、短路透传与合流
算法·leetcode·二叉树··bfs·算法讲解·树遍历
Navigator_Z1 天前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode