Python 从数组中查找3个连续缺失的整数

Python 从数组中查找3个连续缺失的整数,python,arrays,sorting,Python,Arrays,Sorting,下面是查找缺失数字的代码,但需要从缺失中选择前3个连续数字 array=[0,1,4,5,9,10] start=0 end=15 missings=[] for i in range(start,end): if i not in array: missings.append(i) 输出:[6,7,8]给你: array=[0,1,4,5,9,10] start=0 end=15 missings=[] for i in rang

下面是查找缺失数字的代码,但需要从缺失中选择前3个连续数字

array=[0,1,4,5,9,10]
start=0
end=15

missings=[]
for i in range(start,end):        
    if i not in array:
        missings.append(i)
        
输出:[6,7,8]

给你:

array=[0,1,4,5,9,10]
start=0
end=15

missings=[]
for i in range(start,end-1):        
    if i not in array:
        if i+1 not in array:
            if i+2 not in array:
                missings.append(i)
                missings.append(i+1)
                missings.append(i+2)
                break

按升序对列表排序,然后将数组中的值与其相邻值进行比较,以确定是否存在大于3的间隙

def find_missing(arr):
    sorted_list = sorted(arr)
    # Set our lowest value for comparing
    curr_value = sorted_list[0]
    for i in range(1,len(sorted_list)):
        # Compare the previous value to the next value to determine if there is a difference of atleast 4 (6-3 = 3 but we are only missing numbers 4 and 5)
        if (sorted_list[i] - curr_value) > 3:
            # Return on the first 3 consecutive missing numbers
            return [curr_value+1, curr_value+2, curr_value+3]
        curr_value = sorted_list[i]
    # Return an empty array if there is not 3 consecutive missing numbers
    return []
此函数根据数组的长度和最大数工作。如果数组中的所有元素除了最大元素和结束值之外没有三个间隙,则需要指定结束值,可以将其作为参数传递,只需稍作修改

def find_missing(arr, start_val=0, end_val=0):
    # Sorting a list alters the source, so make a copy to not alter the original list
    sorted_list = sorted(arr)
    curr_value = sorted_list[0]
    last_value = sorted_list[-1]
    # Make sure start val is the lowest number, otherwise use lowest number
    if  start_val < curr_value and (curr_value - start_val) > 3:
        return [start_val, start_val+1, start_val+2]
    for i in range(1,len(sorted_list)):
        # Compare the previous value to the next value to determine if there is a difference of atleast 4 (6-3 = 3 but we are only missing numbers 4 and 5)
        if (sorted_list[i] - curr_value) > 3:
            # Return on the first 3 consecutive missing numbers
            return [curr_value+1, curr_value+2, curr_value+3]
        curr_value = sorted_list[i]
    # If there is an end_value set that has a gap between the largest number and is larger than the last value
    if end_val > last_value and (end_val - last_value) > 3:
        return [last_value+1, last_value+2, last_value+3]
    else:
        # Return an empty array if there is not 3 consecutive missing numbers
        return []

你的问题是什么?他的问题是他需要程序的下一步来确定哪3个连续数字缺失。他知道所有缺失的数字,但数组是否已排序且没有重复?您可以尝试使用数组索引:如果数组中的值比其索引大3或更多,则从该索引开始有3个缺失的数字。这有帮助吗?这个网站是为了在你有问题的时候帮助你。我们不是来为您工作并为您提供解决方案的。首先,自己尝试一下,并表现出自己解决问题的努力。提示:使用搜索功能如何检测连续数字。这个问题应该已经在某个地方解决了。