1 回答
TA贡献1843条经验 获得超7个赞
你的逻辑是正确的,除了return里面的陈述if
def find_duplicate(arr):
dup = None # set this to none to act as flag
for i in range(1, len(arr)):
cur = arr[i]
j = i
while j > 0 and arr[j - 1] > cur:
arr[j] = arr[j - 1]
j -= 1
arr[j] = cur
if arr[j-1] == cur:
arr[j] = cur
dup = cur
else:
arr[j] = cur
if dup is None: # check if a duplicate was found
print("no dupes")
return arr
else:
return f"This is the duplicate {dup}, {arr}"
print(find_duplicate([1,-5,3,4,-10,100,250,-325,-5]))
print(find_duplicate([1,-5,3,4,-10,100,250,-325,100]))
print(find_duplicate([1,-5,3,4,-10,100,250,-325,-5,10]))
输出
This is the duplicate -5, [-325, -10, -5, -5, 1, 3, 4, 100, 250]
This is the duplicate 100, [-325, -10, -5, 1, 3, 4, 100, 100, 250]
This is the duplicate -5, [-325, -10, -5, -5, 1, 3, 4, 10, 100, 250]
添加回答
举报