力扣面试题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};
      }
  };
相关推荐
阿崽meitoufa20 分钟前
JVM虚拟机:垃圾收集器和判断对象是否存活的算法
java·jvm·算法
ballball~~1 小时前
拉普拉斯金字塔
算法·机器学习
Cemtery1161 小时前
Day26 常见的降维算法
人工智能·python·算法·机器学习
Ethan-D3 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
Benny_Tang3 小时前
题解:CF2164C Dungeon
c++·算法
仙俊红3 小时前
LeetCode174双周赛T3
数据结构·算法
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——LeetCode 733 题:图像渲染
算法·leetcode·职场和发展
不穿格子的程序员3 小时前
从零开始写算法——回溯篇2:电话号码的字母组合 + 组合总和
算法·深度优先·回溯
持梦远方4 小时前
算法剖析1:摩尔投票算法 ——寻找出现次数超过一半的数
c++·算法·摩尔投票算法
程序员-King.4 小时前
链表——算法总结与新手教学指南
数据结构·算法·链表