Nums = nums[-k:] + nums[:-k]


  • 0
    P
    def rotate(nums, k):
        nums = nums[-k:] + nums[:-k]
    # [1, 2], 1 --> [2, 1]
    # [1, 2, 3, 4, 5, 6, 7], 3 --> [5, 6, 7, 1, 2, 3, 4]
    

    Did I get something wrong? Why wouldn't this work?


  • -1
    R

    I think you did not consider k > len(nums);

    maybe you could do like this:

    def rotate(nums, k):
        k %= len(nums)
        nums = nums[-k:] + nums[:-k]

  • 0
    P

    Thanks for the advice but the case my code fails at
    # [1, 2], 1 --> [2, 1]


Log in to reply
 

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