Why this python code has wrong answer?


  • 0
    H

    My code is as follows:
    """
    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.

       """
        for i in range(k):
             temp=nums[-1]
             del nums[-1]
             nums=[temp]+nums
    

    """

    It runs well in my computer, but it results in a wrong answer when I submit it to leetcode with the test case:

    Input:
    [1]
    1
    Output:
    []
    Expected:
    [1]

    Can anyone tell me why please?


  • 0
    D

    Leetcode seems to have a lot of buggy test cases. Using print, I can see that nums is as expected. But leetcode's code has different output shown.


  • 0
    C

    This is also a common mistake I make. nums=[temp]+nums does not modify noms in-place. You could replace it with nums+=[temp] such that rotate will modify nums in-place instead of make a local copy.


Log in to reply
 

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