从一个序列中找出所有包含全部数字的最小索引区间 -- Python

感jio写的有问题。。先记录一下吧。。

'''
问题:从一个序列中找出所有包含全部数字的最小索引区间,若有多个则按出现的顺序输出。

输入输出示例:
输入:1 1 3 4 6 6 5 1 3 3
输出:[2,7] [3,8] [4,9]
'''


def solution(nums):
    res = []
    # 记录最小区间长度
    d = []
    len_nums = len(nums)
    set_nums = set(nums)
    print(set_nums)
    for i in range(len_nums):
        list_temp = []
        print('i', i)
        for j in range(i, len_nums):
            if nums[j] not in list_temp:
                list_temp.append(nums[j])
            if len(list_temp) == len(set_nums):
                print('j', j)
                print('list_temp', list_temp)
                res.append([i, j])
                d.append(j - i + 1)
                break
        print('----')
    # 找到最短
    r = []
    d_min = min(d)
    for row in res:
        l = row[1] - row[0] + 1
        if l == d_min:
           r.append(row)
    return r


if __name__ == '__main__':
    # nums = [int(i) for i in input().split()]
    nums = [1, 1, 3, 4, 6, 6, 5, 1, 3, 3]
    res = solution(nums)
    print(res)

结果:

[[1, 6], [2, 7], [3, 8]]

note:

这个示例的输出的是序号,我输出的是下标。

想输出序号res.append([i+1, j+1])就好了

猜你喜欢

转载自blog.csdn.net/zdz0200/article/details/82769617