Binary Search

# 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))
``````

### 要不赞赏一下?

 微信 支付宝 PayPal Bitcoin

``https://www.emperinter.info/2022/02/26/binary-search/``

## 优惠码

 阿里云国际版 20美元 Vultr 10美元 搬瓦工 | Bandwagon 应该有折扣吧？ Just My Socks JMS9272283 【注意手动复制去跳转】 域名 | namesilo `emperinter`(1美元) 币安 币安