Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions min_in_sorted_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Find minimum in a rotated sorted array
# This code uses binary search to find the minimum element in a rotated sorted array.
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l,h = 0,len(nums)-1
while l<=h:
mid = (l+h)//2
if nums[l]<=nums[h]:
return nums[l]
elif nums[mid]<nums[mid-1] and nums[mid]<nums[mid+1]:
return nums[mid]
elif nums[l]<=nums[mid]:
l = mid+1
else:
h = mid-1
20 changes: 20 additions & 0 deletions peak_element.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Find peak element in an array
# This code uses binary search to find a peak element in an array
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l,h = 0, len(nums)-1
while l<=h:
mid =(l+h)//2
if (mid==h or nums[mid]>nums[mid+1]) and (mid==l or nums[mid]>nums[mid-1]):
return mid
elif nums[mid]<nums[mid+1]:
l = mid+1
else:
h = mid -1
return -1


38 changes: 38 additions & 0 deletions position_in_sorted_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Find first and last position of element in a sorted array
# #Using two Binary Search to find the first and last position of an element in a sorted array
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def binarySearchFirst(nums,l,h,target):
while l<=h:
mid = (l+h)//2
if nums[mid] == target:
if mid == l or nums[mid]!= nums[mid-1]:
return mid
else:
h = mid-1
elif nums[mid]>target:
h = mid-1
else:
l = mid+1
return -1

def binarySearchLast(nums,l,h,target):
while l<=h:
mid = (l+h)//2
if nums[mid] == target:
if mid == h or nums[mid]!= nums[mid+1]:
return mid
else:
l = mid+1
elif nums[mid]>target:
h = mid-1
else:
l = mid+1

first = binarySearchFirst(nums, 0, len(nums)-1, target)
if first == -1:
return [-1,-1]
last = binarySearchLast(nums, first, len(nums)-1, target)
return [first,last]