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

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

最小连续子数组的和(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;
    }
}

猜你喜欢

转载自blog.csdn.net/u013385925/article/details/83447726
今日推荐