LC 704 - Binary Search
LC 704 - Binary Search
Question
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.
Example 1:
1
2
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2:
1
2
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constraints:
1 <= nums.length <= 104-104 < nums[i], target < 104- All the integers in
numsare unique. numsis sorted in ascending order.
Links
Question here and solution here
Solution
concept
This is an introduction question on binary search, the main to note is that the array has to be sorted first before using binary search.
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def search(self, nums: List[int], target: int) -> int:
l = 0
r = len(nums) - 1
while l <= r:
mid = (l+r)//2
if nums[mid] == target:
return mid
elif nums[mid] > target:
r = mid - 1
else:
l = mid + 1
return -1
Complexity
time: $O(\log n)$
space: $O(\log n)$
we are halving the array each time, the number of times we half the array is $\log_2 n$, which is the number of time our while will run.
This post is licensed under CC BY 4.0 by the author.