-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path39.recover-rotated-sorted-array.py
80 lines (71 loc) · 1.68 KB
/
39.recover-rotated-sorted-array.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Tag: Array, Sort, Simulation
# Time: O(N)
# Space: O(1)
# Ref: -
# Note: Rotated
# Given a **rotated** sorted array, return it to sorted array in-place.(Ascending)
#
# **Example 1:**
#
# Input:
# ```
# array = [4,5,1,2,3]
# ```
# Output:
# ```
# [1,2,3,4,5]
# ```
# Explanation:
#
# Restore the rotated sorted array.
#
# **Example 2:**
#
# Input:
# ```
# array = [6,8,9,1,2]
# ```
# Output:
# ```
# [1,2,6,8,9]
# ```
# Explanation:
#
# Restore the rotated sorted array.
#
# What is rotated array?
#
# - For example, the orginal array is [1,2,3,4], The rotated array of it can be [1,2,3,4], [2,3,4,1], [3,4,1,2], [4,1,2,3]
from typing import (
List,
)
class Solution:
"""
@param nums: An integer array
@return: nothing
"""
def recover_rotated_sorted_array(self, nums: List[int]):
# write your code here
low = self.find_min(nums)
if low > 0:
self.reverse(nums, 0, low - 1)
self.reverse(nums, low, len(nums) - 1)
self.reverse(nums, 0, len(nums) - 1)
def reverse(self, nums: List[int], left: int, right: int):
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
def find_min(self, nums: List[int]) -> int:
left = 0
right = len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] == nums[right]:
right -= 1
continue
if nums[mid] < nums[right]:
right = mid
else:
left = mid + 1
return left