Recursive solution in Python


  • 0

    If you are looking for a recursive solution, there is one.

    class Solution(object):
        def rotate(self, nums, k):
            self.helper(0, len(nums) - 1 - (k % len(nums)), len(nums) - 1, nums) # mid belongs to left part
    
        def helper(self, start, mid, end, nums):
            left, right = mid - start, end - mid - 1
            if left < 0 or right < 0:
                return
            if left > right:
                for j in xrange(mid + 1, end + 1):
                    nums[j], nums[start] = nums[start], nums[j]
                    start += 1
                self.helper(start, mid, end, nums)
            elif right >= left:
                i = mid
                while i >= start:
                    nums[i], nums[end] = nums[end], nums[i]
                    i, end = i - 1, end - 1
                if left != right:
                    self.helper(start, mid, end, nums)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.