Create a complement of list preserving duplicate values

前端 未结 5 1466
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 01:32

Given list a = [1, 2, 2, 3] and its sublist b = [1, 2] find a list complementing b in such a way that sorted(a) == sorted(b + complement)

5条回答
  •  感情败类
    2020-12-11 01:36

    O(n log n)

    a = [1, 2, 2, 3]
    b = [1, 2]
    a.sort()
    b.sort()
    
    L = []
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i] < b[j]:
            L.append(a[i])
            i += 1
        elif a[i] > b[j]:
            L.append(b[j])
            j += 1
        else:
            i += 1
            j += 1
    
    while i < len(a):
        L.append(a[i])
        i += 1
    
    while j < len(b):
        L.append(b[j])
        j += 1
    
    print(L)
    

提交回复
热议问题