leetcode之滑动窗口模板

https://labuladong.gitbook.io/algo/di-ling-zhang-bi-du-xi-lie/hui-su-suan-fa-xiang-jie-xiu-ding-ban
假设你有两个数组,一个长一个短,短的元素均不相同。找到长数组中包含短数组所有的元素的最短子数组,其出现顺序无关紧要。

返回最短子数组的左端点和右端点,如有多个满足条件的子数组,返回左端点最小的一个。若不存在,返回空数组。

示例 1:

输入:
big = [7,5,9,0,2,1,3,5,7,9,1,1,5,8,8,9,7]
small = [1,5,9]
输出: [7,10]
示例 2:

输入:
big = [1,2,3]
small = [4]
输出: []
提示:

  • big.length <= 100000
  • 1 <= small.length <= 100000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-supersequence-lcci

框架代码

 //1. 初始化双指针
	left = 0;
	right = 0;
	while (right < size) {
		//2.扩窗口前,基于right进行窗口内数据的一系列更新
		right++;//3.向右扩展窗口
		//4.判断左侧窗口是否要收缩.第2步更新数据满足目标需求即为窗口移动条件
		while(window needs shrink) {
			//5. 找最短在此判断结果,注意此种模板必须使用左闭右开区间
			size = right - 1 - left + 1;
			if (size < minSize) {
				minSize = size;
				minLeft = left; //左闭
				minRight = righ - 1;//右开
			}
			//6.缩小口前,基于left进行窗口内数据的一系列更新
			left++;//7.缩小窗口
		}
		//8. 返回结果
	}

完整代码

 #define MAX_VAL
 #define MAX_LEN  100000
 int g_hash[MAX_LEN] = { 0 };

void InitHash(int smallSize)
{
    memset(g_hash, 0, smallSize * sizeof(int));

    return;
}
int CheckMatch(int* big,  int* small, int smallSize)
{
    int i;
    int j;

    for (i = 0; i < smallSize; i++) {
        if (g_hash[i] == 0) {
            return 0;
        }
    }
    return 1;
}
int GetHashKey(int val, int* small, int smallSize)
{
    int i;
    for (i = 0; i < smallSize; i++) {
        if (val == small[i]) {
            return i;
        }
    }
    return smallSize;
}
/*
 * 获取最短超串主函数
 */
int* shortestSeq(int* big, int bigSize, int* small, int smallSize, int* returnSize)
{
    int left;
    int right;
    int minWinSize = MAX_VALUE;
    int size;
    int minLeft;
    int minRight;
    //1. 初始化双指针
    left = 0;
    right = 0;
    int * array = NULL;
    int key;

    InitHash(smallSize);
    while (right < bigSize) {
        //2.扩窗口前,进行窗口内数据的一系列更新
        key = GetHashKey(big[right], small, smallSize);
        if (key != smallSize) {
            g_hash[key]++;
        }
        right++;//3. 向右扩展窗口
        while (CheckMatch(big, small, smallSize) == 1) {
            //4. 找最短在此判断结果,注意此种模板必须使用左闭右开区间
            size = right - 1  - left;
            if (size < minWinSize) {
                minWinSize = size;
                minLeft  = left;
                minRight = right - 1;
            }  
            //5.        
            key = GetHashKey(big[left], small, smallSize);
            if (key != smallSize) {
                g_hash[key]--;
            } 
            left++;//向右缩窗口
        }
    }
    if (minWinSize == 65535) {
        *returnSize = 0;
        return NULL;
    }
    
    *returnSize = 2;
    array = (int *)malloc(*returnSize * sizeof(int));
    array[0] = minLeft;
    array[1] = minRight;
    return array;
}

你可能感兴趣的:(leetcode,原创)