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 = 
target = 5

S = Solution()
print(S.search(nums,target))
``````

# 👇 Share | 分享 👇

### 要不赞赏一下?  微信  支付宝  PayPal  Bitcoin

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

## My Github Contributions 