力扣面试题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};
      }
  };
相关推荐
im_AMBER15 小时前
Leetcode 79 最佳观光组合
笔记·学习·算法·leetcode
高山上有一只小老虎15 小时前
小红背单词
java·算法
练习时长一年15 小时前
在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
资深web全栈开发16 小时前
LeetCode 3573. 买卖股票的最佳时机 V - 动态规划解法详解
算法·leetcode·动态规划
leiming616 小时前
C++ 01 函数模板
开发语言·c++·算法
Chen--Xing16 小时前
LeetCode LCR 119.最长连续序列
c++·python·算法·leetcode·rust
金枪不摆鳍16 小时前
算法2-链表
数据结构·算法·链表
yeshihouhou16 小时前
redis数据分片算法
redis·算法·哈希算法
天才测试猿16 小时前
Jmeter 命令行压测&生成HTML测试报告
自动化测试·软件测试·python·测试工具·jmeter·职场和发展·jenkins
李余博睿(新疆)16 小时前
c++经典练习题-分支练习(1)
数据结构·c++·算法