力扣面试题17.18.最短超串

力扣面试题17.18.最短超串

  • 类似76.

  • 用哈希表处理短数组 然后遍历长数组

    • 找到相同元素 count-- --
    • 当count==0时进入循环 ------ 尽可能缩小区间
cpp 复制代码
  class Solution {
  public:
      vector<int> shortestSeq(vector<int>& big, vector<int>& small) {
          int n=big.size(),m=small.size();
          int st=-1,ed=n;
          unordered_map<int,int> cnt;
          int count=0;  //记录small中元素个数
          for(auto c:small)
          {
              if(!cnt.count(c)) count++;
              cnt[c] ++;
          }
          for(int i=0,j=0;i<n;i++)
          {
              cnt[big[i]] --;
              if(cnt[big[i]] == 0) count--;
              while(!count)
              {
                  cnt[big[j]] ++;
                  //说明当前左端点为small中元素 并且big的区间内已不包含
                  if(cnt[big[j]] >0)
                  {
                      count++;
                      if(ed - st > i - j) st = j,ed = i;
                  }
                  j ++;
              }
          }
          if(st == -1) return {};
          else return {st,ed};
      }
  };
相关推荐
历程里程碑24 分钟前
C++ 10 模板进阶:参数特化与分离编译解析
c语言·开发语言·数据结构·c++·算法
星辞树1 小时前
从 In-context Learning 到 RLHF:大语言模型的范式跃迁
算法
再__努力1点1 小时前
【68】颜色直方图详解与Python实现
开发语言·图像处理·人工智能·python·算法·计算机视觉
mingchen_peng1 小时前
第一章 初识智能体
算法
百锦再1 小时前
国产数据库的平替亮点——关系型数据库架构适配
android·java·前端·数据库·sql·算法·数据库架构
晨曦夜月2 小时前
笔试强训day5
数据结构·算法
H_z___2 小时前
Hz的计数问题总结
数据结构·算法
她说彩礼65万2 小时前
C# 反射
java·算法·c#
练习时长一年2 小时前
LeetCode热题100(搜索插入位置)
数据结构·算法·leetcode