← 返回 apple 的题目列表Python Debugging — Fix a Loop Condition Bug
类型:online_judge
Problem: Python Debug — Fix a loop-condition bug
You are given a Python function intended to return the index of target in a sorted array nums, or -1 if not found.
The current implementation has a loop condition / boundary bug that may cause:
an infinite loop, or
incorrect results on edge cases.
Fix the loop condition/boundary updates while keeping the same overall approach (binary search).
Buggy code
def search(nums, target):
l, r = 0, len(nums) - 1
while l < r: # BUG: loop condition / boundary
mid = (l + r) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
l = mid # BUG: may not progress
else:
r = mid # BUG: may not progress
return -1
Input
Line 1: integer n
Line 2: n sorted integers (strictly increasing)
Line 3: integer target
Output
An integer: 0-based index of target, or -1.
Constraints
0 ≤ n ≤ 2*10^5
nums is strictly increasing.
Example
Input
5
1 3 5 7 9
7
Output
3