Skip to content

Commit ecf16ce

Browse files
Chris WuChris Wu
authored andcommitted
bisect
1 parent 9fa9d08 commit ecf16ce

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

problems/binary-search.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
Continue this proccess, until we find the value.
1010
1111
If we can't find the value, then `l` and `r` are going to collapse. `return -1`
12+
13+
Another solution is to use [bisect](https://docs.python.org/2.7/library/bisect.html).
1214
"""
1315
class Solution(object):
1416
def search(self, nums, target):
@@ -28,3 +30,15 @@ def search(self, nums, target):
2830
else:
2931
l = p+1
3032
return -1
33+
34+
import bisect
35+
class Solution(object):
36+
def search(self, nums, target):
37+
if nums is None or len(nums)==0: return -1
38+
if target<nums[0] or nums[-1]<target: return -1 #check if out of range
39+
40+
i = bisect.bisect_left(nums, target)
41+
42+
#check if target in `nums`
43+
if nums[i]==target: return i
44+
else: return -1

problems/find-first-and-last-position-of-element-in-sorted-array.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
Second, we move pointers, `l`, `r` to find the right-most and left-most targets.
1010
1111
The time complexity is O(LogN), becuase we use the concept of binary search to find the `target`.
12+
13+
Another solution is to use [bisect](https://docs.python.org/2.7/library/bisect.html).
1214
"""
1315
class Solution(object):
1416
def searchRange(self, nums, target):
@@ -33,3 +35,16 @@ def searchRange(self, nums, target):
3335
while 0<=l-1 and nums[l-1]==target:
3436
l = l-1
3537
return [l, r]
38+
39+
40+
import bisect
41+
class Solution(object):
42+
def searchRange(self, nums, target):
43+
if nums is None or len(nums)==0: return [-1, -1]
44+
if target<nums[0] or nums[-1]<target: return [-1, -1] #check if target out of range
45+
l = bisect.bisect_left(nums, target)
46+
r = bisect.bisect_right(nums, target)
47+
48+
if nums[l]!=target or nums[r-1]!=target: return [-1, -1] #check if target in `nums`
49+
return [l, r-1]
50+

0 commit comments

Comments
 (0)