这是我的代码
for i in range(len(nums) - 1):
if all(num > target for num in nums[i + 1:]):
return i
return -1
当我输入目标2和[1,2,2,3,4]列表时,它应该输出3但它返回2,并输入7的目标和[7,8,9,10列表,12]它应该输出 4 但它返回 0。我该如何修复它以便它输出正确的输出
您的代码的问题在于,在查看当前元素(nums[i])之后的元素之前,它不会检查当前元素(nums[i])是否小于或等于目标。试试这个:
def find_index(nums, target):
for i in range(len(nums) - 1):
if nums[i] <= target and all(num > target for num in nums[i + 1:]):
return i + 1
return -1
我添加了 nums[i] <= target to ensure you're only considering indices where the current element isn't already greater than the target.