Leetcode之面试题17.18——最短超串

题目:

假设你有两个数组,一个长一个短,短的元素均不相同。找到长数组中包含短数组所有的元素的最短子数组,其出现顺序无关紧要。

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

示例 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

代码:

class Solution {
public:
    vector<int> shortestSeq(vector<int>& big, vector<int>& small) {
        vector<int> res;
        unordered_map<int, int> hashSmall;
        int count = 0, j = 0;
        for (auto e : small) {
            if (!hashSmall.count(e)) count++; 
            hashSmall[e]++;
        }
        for (int i = 0; i < big.size(); i++) {
            hashSmall[big[i]]--;
            if (hashSmall[big[i]] == 0) count--;
            while (!count) {
                hashSmall[big[j]]++; 
                if (hashSmall[big[j]] > 0) {
                    count++;
                    if (res.empty() || res[1] - res[0] > i - j) res = {j, i};
                }
                j ++;
            }
        }
        return res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值