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)
相关推荐
xlp666hub4 小时前
Leetcode 第三题:用C++解决最长连续序列
c++·leetcode
xlp666hub7 小时前
Leetcode第二题:用 C++ 解决字母异位词分组
c++·leetcode
xlp666hub1 天前
Leetcode第一题:用C++解决两数之和问题
c++·leetcode
琢磨先生David11 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝11 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll11 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐11 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶11 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER11 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了11 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表