三种方法解决Lintcode39 Recover Rotated Sorted Array in Python

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值