力扣面试题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};
      }
  };
相关推荐
七禾页丫8 分钟前
面试记录12 中级c++开发工程师
c++·面试·职场和发展
wifi chicken26 分钟前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
胡楚昊38 分钟前
NSSCTF动调题包通关
开发语言·javascript·算法
Gold_Dino1 小时前
agc011_e 题解
算法
bubiyoushang8882 小时前
基于蚁群算法的直流电机PID参数整定 MATLAB 实现
数据结构·算法·matlab
风筝在晴天搁浅2 小时前
hot100 240.搜索二维矩阵Ⅱ
算法·矩阵
girl-07262 小时前
2025.12.24代码分析
算法
永远睡不够的入2 小时前
直接插入排序、希尔排序、选择排序
数据结构·算法·排序算法
历程里程碑2 小时前
hot 206
java·开发语言·数据结构·c++·python·算法·排序算法
Tipriest_3 小时前
C++ 的 ranges 和 Python 的 bisect 在二分查找中的应用与实现
c++·python·算法·二分法