Python O(n) time and O(1) space


  • -2
    Y
    class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        if n <=0 or k <= 0:
            return
        
        i = 0
        pos = 0
        prev = nums[0]
        start_pos = 0
        while i < n:
            new_pos = (pos + k) % n
            current = nums[new_pos]
            nums[new_pos] = prev
    
            prev = current
            i += 1
            
            #if there is a loop, break it
            if new_pos == start_pos:
                start_pos = (start_pos + 1) % n
                pos = start_pos
                prev = nums[pos]
            else:
                pos = new_pos

Log in to reply
 

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