📅  最后修改于: 2023-12-03 15:26:11.651000             🧑  作者: Mango
给出一个长度为n(n>=2)的整数序列,序列中可能缺少某个数字的出现。现在要在序列中插入一个数字,使得相邻元素的最大绝对差最小。
思路一:二分答案
思路二:贪心
以下为二分答案的代码实现:
def searchInsert(nums: List[int], target: int) -> int:
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left
def insertMissingNumber(nums: List[int]) -> int:
n = len(nums)
maxn = max(abs(nums[i] - nums[i-1]) for i in range(1, n))
left, right = 0, maxn
while left < right:
mid = left + (right - left) // 2
i = searchInsert(nums, nums[0] + mid)
if i == n or nums[i] > nums[0] + mid:
i -= 1
if abs(nums[i] - nums[0] - mid) <= maxn and abs(nums[i+1] - nums[0] - mid) <= maxn:
return nums[0] + mid
elif abs(nums[i+1] - nums[0] - mid) > maxn:
left = mid + 1
else:
right = mid
return nums[0] + left
以下为贪心的代码实现:
def searchCnt(nums: List[int], mid: int) -> Tuple[int, int]:
cnt1, cnt2 = 0, 0
for num in nums:
if num <= mid:
cnt1 += 1
else:
cnt2 += 1
return cnt1, cnt2
def insertMissingNumber(nums: List[int]) -> int:
n = len(nums)
left, right = min(nums), max(nums) + 1
while left < right:
mid = (left + right) // 2
cnt1, cnt2 = searchCnt(nums, mid)
if cnt1 > cnt2:
right = mid
else:
left = mid + 1
return left
本题时间复杂度为O(nlogn),空间复杂度为O(1),可以通过本题。二分答案和贪心思路均可解决此问题。