文章目录[隐藏]
Description
Given an array of integers nums
which is sorted in ascending order, and an integer target
, write a function to search target in nums
. If target exists, then return its index. Otherwise, return -1
.
You must write an algorithm with O(log n) runtime complexity.
Code
- submit code
class Solution:
def search(self, nums: List[int], target: int) -> int:
left = 0
right = len(nums) - 1
while(left <= right):
mid = left + int((right - left) / 2)
if(nums[mid] == target):
return mid
elif(nums[mid] > target):
right = mid - 1
elif(nums[mid] < target):
left = mid + 1
return -1
- full code
class Solution:
def search(self, nums, target):
left = 0
right = len(nums) - 1
while(left <= right):
mid = left + int((right - left ) / 2)
print(mid)
if(nums[mid] == target):
return mid
elif(nums[mid] < target):
left = mid + 1
elif(nums[mid] > target):
right = mid - 1
return -1
nums = [5]
target = 5
S = Solution()
print(S.search(nums,target))