力扣面试题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};
      }
  };
相关推荐
元亓亓亓10 小时前
LeetCode热题100--416. 分割等和子集--中等
算法·leetcode·职场和发展
BanyeBirth10 小时前
C++差分数组(二维)
开发语言·c++·算法
xu_yule12 小时前
算法基础(数论)—算法基本定理
c++·算法·算数基本定理
CoderCodingNo12 小时前
【GESP】C++五级真题(结构体排序考点) luogu-B3968 [GESP202403 五级] 成绩排序
开发语言·c++·算法
YGGP13 小时前
【Golang】LeetCode 32. 最长有效括号
算法·leetcode
自然常数e14 小时前
字符函数和字符串函数
c语言·算法·visual studio
leaves falling14 小时前
c语言分数求和
算法
Das114 小时前
【机器学习】01_模型选择与评估
人工智能·算法·机器学习
星轨初途14 小时前
郑州轻工业大学2025天梯赛解题
c++·经验分享·笔记·算法·链表·剪枝