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)
相关推荐
blxr_5 小时前
力扣hot100前k个高频元素https://leetcode.cn/problems/top-k-frequent-elements/
算法·leetcode·职场和发展
longlongzihan14 小时前
LeetCode 17电话号码的字母组合:回溯算法(DFS)详解
c++·算法·leetcode·深度优先
smj2302_7968265220 小时前
解决leetcode第4064题至多一次取反能被k整除的最长子数组II
python·算法·leetcode
青山木21 小时前
Hot 100 --- 下一个排列
java·数据结构·算法·leetcode
垆边人似月.21 小时前
字符串重排后最大字典序
算法·leetcode·职场和发展
代码什么用1 天前
LeetCode-42. 接雨水
算法·leetcode
yi0111 天前
DAY17: LeetCode 139|单词拆分:从“把单词删掉”到用 DP 记录合法切口
人工智能·笔记·python·算法·leetcode·动态规划
Navigator_Z1 天前
LeetCode //C - 1269. Number of Ways to Stay in the Same Place After Some Steps
c语言·算法·leetcode
垆边人似月.1 天前
华为算法题:最长连续递增子序列的变
数据结构·算法·leetcode
longlongzihan1 天前
LeetCode 56合并区间:排序与贪心
c++·算法·leetcode