[
binary search
]
Leetcode 0704. Binary Search
https://leetcode.com/problems/binary-search
We just need to do what is asked in the name of this problem: binary search! Also we need to find index of found element, so we check 3
conditions: nums[mid] == target
, nums[mid] < target
and nums[mid] > target
.
Complexity is O(log n)
, classical complexity of binary search, because on each step we reduce searching region twice.
class Solution:
def search(self, nums, target):
beg, end = 0, len(nums) - 1
while beg <= end:
mid = (beg + end)//2
if nums[mid] == target: return mid
if nums[mid] < target:
beg = mid + 1
else:
end = mid - 1
return -1
If you like the solution, you can upvote it on leetcode discussion section: Problem 0704