Tuesday, August 25, 2015

Leetcode 189. Rotate Array

https://leetcode.com/problems/rotate-array/

Many ways to solve it.

Solution:
# T:O(n) S:O(1)
class Solution:
    # @param nums, a list of integer
    # @param k, num of steps
    # @return nothing, please modify the nums list in-place.
    def rotate(self, nums, k):
        k %= len(nums)
        self.reverse(nums, 0, len(nums))
        self.reverse(nums, 0, k)
        self.reverse(nums, k, len(nums))
    
    def reverse(self, nums, start, end):
        while start < end:
            nums[start], nums[end-1] = nums[end-1], nums[start]
            start += 1
            end -= 1
Run Time: 88 ms

No comments:

Post a Comment