Efficient way to find missing elements in an integer sequence

前端 未结 16 1376
鱼传尺愫
鱼传尺愫 2020-12-01 04:32

Suppose we have two items missing in a sequence of consecutive integers and the missing elements lie between the first and last elements. I did write a code that does accomp

16条回答
  •  难免孤独
    2020-12-01 05:13

    arr = [1, 2, 5, 6, 10, 12]
    diff = []
    
    """zip will return array of tuples (1, 2) (2, 5) (5, 6) (6, 10) (10, 12) """
    for a, b in zip(arr , arr[1:]):
        if a + 1 != b:
            diff.extend(range(a+1, b))
    
    print(diff)
    

    [3, 4, 7, 8, 9, 11]

    If the list is sorted we can lookup for any gap. Then generate a range object between current (+1) and next value (not inclusive) and extend it to the list of differences.

提交回复
热议问题