📅  最后修改于: 2023-12-03 15:21:54.736000             🧑  作者: Mango
给定一个整数N,和一个目标值S,找到从1到N中删除两个连续的整数,使得剩余数的总和等于S。如果无法找到这样的两个数字,则返回一个空列表。
def find_continuous_numbers(n: int, s: int) -> list:
sum_total = (n * (n + 1)) // 2 # 1到n的整数和
sum_remove = sum_total - s # 需要删除的两个数的和
if sum_remove % 2 != 0:
return [] # 需要删除的两个数的和必须是偶数
x = ((sum_total - s) // 2)
if x <= 0 or x >= n:
return [] # 没有合法的解
result = []
for i in range(1, n+1):
if i == x or i == x+1:
continue
result.append(i)
return result
assert find_continuous_numbers(10, 15) == [1, 2, 3, 4, 5]
assert find_continuous_numbers(10, 11) == [1, 2, 3, 4, 6, 7, 8, 9, 10]
assert find_continuous_numbers(5, 5) == [2, 3, 4, 5]
assert find_continuous_numbers(10, 100) == []
assert find_continuous_numbers(2, 4) == []