一:面试题 17.18. 最短超串 来源:力扣(LeetCode)
(https://leetcode.cn/problems/shortest-supersequence-lcci/)
假设你有两个数组,一个长一个短,短的元素均不相同。找到长数组中包含短数组所有的元素的最短子数组,其出现顺序无关紧要。
返回最短子数组的左端点和右端点,如有多个满足条件的子数组,返回左端点最小的一个。若不存在,返回空数组。
输入: big = [7,5,9,0,2,1,3,5,7,9,1,1,5,8,8,9,7] small = [1,5,9]
输出: [7,10]输入:big = [1,2,3]small = [4]
输出: []
import collections
big = [7, 5, 9, 0, 2, 1, 3, 5, 7, 9, 1, 1, 5, 8, 8, 9, 7]
small = [1,5,9]
n = len(big)
need = len(small)
min_lens = n+1
res = []
left = right = 0
cnt = collections.Counter(small)
for right in range(n):
num = big[right]
if num in cnt:
if cnt[num] > 0:
need -= 1
cnt[num] += 1
while need == 0:
if right - left + 1 < min_lens:
min_lens = right - left +1
res = [left,right]
num = big[left]
if num in cnt:
if cnt[num] >= 0:
need +=1
cnt[num] += 1
left += 1
print(res)
同类题型:
76. 最小覆盖子串
题解:https://leetcode.cn/problems/minimum-window-substring/solution/by-flix-1kac/