Skip to content

Commit 4cea1bc

Browse files
authored
Create binary-search.py
1 parent f3784e8 commit 4cea1bc

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Python/binary-search.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(logn)
2+
# Space: O(1)
3+
4+
# Given a sorted (in ascending order) integer array nums of n elements
5+
# and a target value, write a function to search target in nums.
6+
# If target exists, then return its index, otherwise return -1.
7+
#
8+
# Example 1:
9+
#
10+
# Input: nums = [-1,0,3,5,9,12], target = 9
11+
# Output: 4
12+
# Explanation: 9 exists in nums and its index is 4
13+
#
14+
# Example 2:
15+
#
16+
# Input: nums = [-1,0,3,5,9,12], target = 2
17+
# Output: -1
18+
# Explanation: 2 does not exist in nums so return -1
19+
#
20+
# Note:
21+
# - You may assume that all elements in nums are unique.
22+
# - n will be in the range [1, 10000].
23+
# - The value of each element in nums will be in the range [-9999, 9999].
24+
25+
26+
class Solution(object):
27+
def search(self, nums, target):
28+
"""
29+
:type nums: List[int]
30+
:type target: int
31+
:rtype: int
32+
"""
33+
left, right = 0, len(nums)-1
34+
while left <= right:
35+
mid = left + (right-left)//2
36+
if nums[mid] > target:
37+
right = mid-1
38+
elif nums[mid] < target:
39+
left = mid+1
40+
else:
41+
return mid
42+
return -1

0 commit comments

Comments
 (0)