Rotate Array

Problem: Rotate Array

Through observation we can get that rotating array is just moving the last k numbers to the head of array.

Code in Python:

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.
        """
        l = nums[:len(nums)-k]
        r = nums[len(nums)-k:]
        nums[:] = r + l

Details:

  • To do in place modification, we cannot only assign new array to num, or we will only modify the reference of the array. We need to use nums[:] to modify the values in the array.

results matching ""

    No results matching ""