1. 三次翻转
首先找到最小值的index,而后翻转三次。for example, [4,5,1,2,3], 先找到1的index2,再以2为轴:
[4,5]->[5,4]; [1,2,3]->[3,2,1]; [5,4,3,2,1]->[1,2,3,4,5]
class Solution:
"""
@param nums: An integer array
@return: nothing
"""
def recoverRotatedSortedArray(self, nums):
pos = nums.index(min(nums))
self.reverse(nums,0,pos-1)
self.reverse(nums,pos,len(nums)-1)
self.reverse(nums,0,len(nums)-1)
def reverse(self,nums,left,right):
while left<right:
temp=nums[left]
nums[left]=nums[right]
nums[right]=temp
left += 1
right -= 1
2. 直接找到最小值的index,而后append此index之前的element to list,同时remove element in front of min.
def recoverRotatedSortedArray(self, nums):
# write your code here
pos = nums.index(min(nums))
i = 0
for i in range(pos):
nums.append(nums[0])
nums.remove(nums[0])
i += 1
3. 直接sort
class Solution:
"""
@param nums: An integer array
@return: nothing
"""
def recoverRotatedSortedArray(self, nums):
nums.sort()
4. 当我看见rotated就想用binary search, 但本题不适用,因为这里的list可能会有重复元素,若事先说明没有duplicate,binary search也是一种解决方法。
def recoverRotatedSortedArray(nums):
# write your code here
if len(nums)==0:
return nums
left = 0
right = len(nums)-1
while left+1<right:
mid = (left+right)//2
if nums[mid] <= nums[mid-1]:
right = mid
else:
left = mid
i = 0
if nums[left]<nums[right]:
nums=nums
else:
for i in range(right):
nums.append(nums[0])
nums.remove(nums[0])
return nums