题目:
案例解析:
下标 | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|---|
数值 | -1 | 2 | 4 | 7 | 9 | 11 | 13 |
target:9
关键条件:数组是有序(升序)排列
代码实现(二分法):
left = 0
right = len(nums)-1
while left <= right:
center = (left+right)/2
if(nums[center] < target):
left = center+1
if(nums[center] > target):
right = center-1
if(nums[center] == target):
return center
return -1
代码实现(暴力法):
for i in nums:
if i==target:
return nums.index(i)
if i==nums[-1]:
return -1