题目描述
Given a sorted (in ascending order) integer array nums of n
elements and a target
value, write a function to search target
in nums
. If target
exists, then return its index, otherwise return -1
.
样例
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
算法1
(二分查找) $O(logn)$
class Solution:
def search(self, nums: List[int], target: int) -> int:
index = bisect.bisect_left(nums, target)
return index if index < len(nums) and nums[index] == target else -1
"""
# 手写二分查找
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] < target:
l = mid + 1
elif nums[mid] > target:
r = mid - 1
else:
return mid
return -1
"""
"""
res = 0
for i, item in enumerate(nums):
if target == item:
return i
res += 1
if res == 0: return -1
"""