Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6755655

Browse files
authored
Create Day-31_Find_minimum_in_rotated_sorted_array.py
1 parent e825772 commit 6755655

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Linear Search - O(N)
2+
# Binary Search - O(logN)
3+
4+
class Solution:
5+
def findMin(self, nums: List[int]) -> int:
6+
# Special cases
7+
# If only one element
8+
if len(nums) == 1:
9+
return nums[0]
10+
# If not rotated. How do we know ? If nums[0] < nums[n-1]
11+
if nums[0] < nums[-1]:
12+
return nums[0]
13+
14+
# Binary Search
15+
low, high = 0, len(nums) - 1
16+
while low <= high:
17+
mid = (low + high)//2
18+
if nums[mid] < nums[low]:
19+
# Check for inflection point on the left side
20+
high = mid - 1
21+
else:
22+
# Check for inflection point on the right side
23+
low = mid + 1
24+
if nums[mid] > nums[mid+1]:
25+
return nums[mid+1]
26+
if nums[mid] < nums[mid - 1]:
27+
return nums[mid]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /