Find shortest subarray containing all elements

后端 未结 6 662
执念已碎
执念已碎 2020-12-13 04:42

Suppose you have an array of numbers, and another set of numbers. You have to find the shortest subarray containing all numbers with minimal complexity.

The array ca

6条回答
  •  情书的邮戳
    2020-12-13 05:29

    Here's how I solved this problem in linear time using collections.Counter objects

    from collections import Counter
    
    def smallest_subsequence(stream, search):
        if not search:
            return []  # the shortest subsequence containing nothing is nothing
    
        stream_counts = Counter(stream)
        search_counts = Counter(search)
    
        minimal_subsequence = None
    
        start = 0
        end = 0
        subsequence_counts = Counter()
    
        while True:
            # while subsequence_counts doesn't have enough elements to cancel out every
            # element in search_counts, take the next element from search
            while search_counts - subsequence_counts:
                if end == len(stream):  # if we've reached the end of the list, we're done
                    return minimal_subsequence
                subsequence_counts[stream[end]] += 1
                end += 1
    
            # while subsequence_counts has enough elements to cover search_counts, keep
            # removing from the start of the sequence
            while not search_counts - subsequence_counts:
                if minimal_subsequence is None or (end - start) < len(minimal_subsequence):
                    minimal_subsequence = stream[start:end]
                subsequence_counts[stream[start]] -= 1
                start += 1
    
    print(smallest_subsequence([1, 2, 5, 8, 7, 6, 2, 6, 5, 3, 8, 5], [5, 7]))
    # [5, 8, 7]
    

提交回复
热议问题