nums,target = input().split() List = input() class Solution: def search(self, nums: List[int], target: int) -> int: first,last = 0,len(nums) while first<last: #左闭右开,first不会等于last[first,last) mid_index = (first+last) // 2 if nums[mid_index]<target: first = mid_index+1 elif nums[mid_index]>target: last = mid_index #注意与第一种方法的区别,last为开区间 else: return mid_index return len(nums)+1改正
时间: 2024-02-14 12:35:47 浏览: 347
js代码-两数之和 输入:nums = [2,7,11,15], target = 9 输出:[0,1]
nums, target = input().split()
List = input().split() # 将字符串转换为列表,方便后续操作
class Solution:
def search(self, nums: List[int], target: int) -> int:
first, last = 0, len(nums)
while first < last:
mid_index = (first + last) // 2
if nums[mid_index] < target:
first = mid_index + 1
elif nums[mid_index] > target:
last = mid_index
else:
return mid_index
return -1 # 如果没有找到目标值,则返回 -1
# 创建 Solution 类的实例
s = Solution()
# 将输入的 List 中的字符串转换为整数
nums = [int(num) for num in List]
# 调用 search 方法,输出结果
print(s.search(nums, int(target)))
阅读全文