最小的窗口包含数组中的所有元素

时间:2018-08-16 05:04:19

标签: python algorithm

我需要编写一个函数来查找包含数组中所有元素的最小窗口。下面是我尝试过的:

def function(item):
    x = len(set(item))
    i = 0
    j = len(item) - 1
    result = len(item)
    while i <= j:
        if len(set(item[i + 1: j + 1])) == x:
            result = min(result, len(item[i + 1: j + 1]))
            i += 1 
        elif len(set(item[i:j])) == x:
            result = min(result, len(item[i:j]))
            j -= 1
        else:
            return result
    return result

print(function([8,8,8,8,1,2,5,7,8,8,8,8]))

时间复杂度为O(N ^ 2),有人可以帮助我将其提高到O(N)或更好吗?谢谢。

2 个答案:

答案 0 :(得分:0)

您可以将How to find smallest substring which contains all characters from a given string?中的想法用于此特定情况,并获得O(N)解决方案。

保留一个计数器,以了解窗口中包含每个唯一编号的副本数,并将窗口的结尾向右移动,直到至少一次包含所有唯一编号。然后移动窗口的开始,直到一个唯一的数字消失。然后重复:

from collections import Counter
def smallest_window(items):
    element_counts = Counter()
    n_unique = len(set(items))
    characters_included = 0
    start_enumerator = enumerate(items)
    min_window = len(items)
    for end, element in enumerate(items):
        element_counts[element] += 1
        if element_counts[element] == 1:
            characters_included += 1
        while characters_included == n_unique:
            start, removed_element = next(start_enumerator)
            min_window = min(end-start+1, min_window)
            element_counts[removed_element] -= 1
            if element_counts[removed_element] == 0:
                characters_included -= 1
    return min_window 

>>> smallest_window([8,8,8,8,1,2,5,7,8,8,8,8])
5

答案 1 :(得分:0)

此问题可以通过以下方法解决。

def lengthOfLongestSublist(s):
    result = 0
    #set a dictionary to store item in s as the key and index as value
    d={}
    i=0
    j=0
    while (j < len(s)):
        #if find the s[j] value is already exist in the dictionary,
        #move the window start point from i to i+1
        if (s[j] in d):
            i = max(d[s[j]] + 1,i)
        #each time loop, compare the current length of s to the previouse one
        result = max(result,j-i+1)
        #store s[j] as key and the index of s[j] as value
        d[s[j]] = j
        j = j + 1
    return result

lengthOfLongestSubstring([8,8,8,8,8,5,6,7,8,8,8,8,])

Output: 4
  1. 设置字典以将输入列表的值存储为键和索引 列表中的值。 dic[l[j]]=j

  2. 在循环中,查找字典中是否存在当前值。如果 如果存在,请将起点从i移至i + 1

  3. 更新结果。

复杂度为O(n)。