012-算法面试必备-滑动窗口的技巧

本文深入探讨了滑动窗口算法的应用,通过两道LeetCode题目——最小连续子数组的和与无重复字符的最长子串,详细讲解了如何利用滑动窗口解决实际问题。文章提供了清晰的代码示例,帮助读者理解并掌握这一高效算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天说说滑动窗口的技巧。介绍两个题

最小连续子数组的和(minimum size subarray sum)

这是leetcode 209题

描述:

给定一个整形数组和一个数字s

找到数组中最短的一个连续子数组,使得连续子数组的和sum >= s

返回这个最短的连续子数组的长度值

比如:给定数组【2,3,1,2,4,3】,s = 7

答案为【4,3】,因此返回2

 

解题:

采用滑动窗口的方法

//滑动窗口
class Solution_ShortestLen1014{
	public int getLen(int[] arr,int s){
		int n = arr.length;
		int i = 0;
		int j = -1;   //上来这个窗口是不存在的
		int sum = 0;
		int minLen = n+1;
		while(i<n){
			if(j+1<n&&sum<s){
				j++;
				sum = sum + arr[j];  //如果满足条件就sum+
			}else{
				sum = sum -arr[i];
				i++;
			}
			if(sum>=s){
				minLen = Math.min(minLen,j-i+1);  //这里是索引进行相加
			}
		}
		if(minLen == n+1)return 0;
		return minLen;
		
	}
}

下面说另一道题

leetcode 3题

longest substring without repeating words

在一个字符串中,寻找没有重复字符的最长连续子串,返回其长度。

下面来看几个例子

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc", with the length of 3. 

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3. 
             Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

直接看代码吧。

import java.util.LinkedList;
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        int i = 0;
        int j = -1;
        int minLen = 0;
        LinkedList<Character> ls = new LinkedList<Character>();
        while(i<n){
            if(j+1<n&&!ls.contains(s.charAt(j+1))){
                j++;
                ls.addLast(s.charAt(j));
            }else{
                ls.removeFirst();
                i++;
            }
            minLen = Math.max(minLen,j-i+1);
        }
        return minLen;
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值