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)
相关推荐
想吃火锅10054 小时前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil2085 小时前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
evans在进步10 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil20810 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
吃着火锅x唱着歌11 小时前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王11 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
小星星闪亮登场12 小时前
2026河南萌新联赛第四场--南阳理工学院
数据结构·算法·贪心算法·动态规划·哈希算法·广度优先
土司大王12 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode
.道阻且长.13 小时前
7.LeetCode算法习题讲解--双指针--四数之和
算法·leetcode·职场和发展
Navigator_Z13 小时前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode