LeetCode704 Binary Search
Author: Stefan Su
Create time: 2022-10-26 02:11:25
Location: New York City, NY, USA
Description Easy
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
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4
Example 2
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1
Constrains
1 <= nums.length <= 10^4
-10^4 < nums[i], target < 10^4
- All the integers in
nums
are unique nums
is sorted in ascending order
Analysis
First, we should know what binary search is. It is a search algorithm for a sorted array to find the index of a given target value. Generally, we do operation in the array’s indices. We can consider this problem in two ways. [left, right]
or [left, right)
.
Remember, always pay attention on the while condition and the move of index in the while loop.
Solution
[left, right]
version
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# [left, right]
left = 0
right = len(nums) - 1
while left <= right: # we consider nums[left] == nums[right] is meaningful, so use <=
middle = int((left + right) / 2)
if nums[middle] < target:
left = middle + 1 # key operation
elif nums[middle] > target:
right = middle - 1 # key operation
else:
return middle
return -1
[left, right)
version
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# [left, right)
left = 0
right = len(nums)
while left < right: # we consider nums[len(nums)] is out of index
middle = int((left + right) / 2)
if nums[middle] < target:
left = middle + 1 # key operation
elif nums[middle] > target:
right = middle # key operation
else:
return middle
return -1
Hopefully, this blog can inspire you when solving LeetCode704. For any questions, please comment below.