Skip to content

Commit 3872ae0

Browse files
committed
Insertion Sort/ Find Minimum in Rotated Sorted Array
1 parent 8c2574f commit 3872ae0

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

147 Insertion Sort List.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Sort a linked list using insertion sort.
3+
'''
4+
5+
# Definition for singly-linked list.
6+
class ListNode(object):
7+
def __init__(self, x):
8+
self.val = x
9+
self.next = None
10+
11+
12+
class Solution(object):
13+
def insertionSortList(self, head):
14+
"""
15+
:type head: ListNode
16+
:rtype: ListNode
17+
"""
18+
dummy = ListNode(-1)
19+
cur = dummy
20+
while head:
21+
# check if it is needed to reset the cur pointer
22+
if cur and cur.val > head.val:
23+
cur = dummy
24+
# find the place to insert
25+
while cur.next and cur.next.val < head.val:
26+
cur = cur.next
27+
# insert and sort the next element
28+
cur.next, cur.next.next, head = head, cur.next, head.next
29+
return dummy.next
30+
31+
32+
if __name__ == "__main__":
33+
None
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
3+
4+
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
5+
6+
Find the minimum element.
7+
8+
You may assume no duplicate exists in the array.
9+
'''
10+
11+
class Solution(object):
12+
def findMin(self, nums):
13+
"""
14+
:type nums: List[int]
15+
:rtype: int
16+
"""
17+
left, right = 0, len(nums) - 1
18+
mid = 0
19+
while left < right:
20+
mid = (left + right) // 2
21+
if nums[mid] > nums[mid + 1]:
22+
return nums[mid + 1]
23+
elif nums[mid] > nums[right]:
24+
left = mid + 1
25+
else:
26+
right = mid
27+
return nums[mid]
28+
29+
30+
if __name__ == "__main__":
31+
assert Solution().findMin([1, 2, 3, 4, 5]) == 1
32+
assert Solution().findMin([2, 3, 4, 5, 1]) == 1
33+
assert Solution().findMin([5, 1, 2, 3, 4]) == 1

0 commit comments

Comments
 (0)