I am a beginner.
I don't know why my code has wrong answer on:
Input: [1,2], 1
Can someone tell me why? please
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) if nums is None: return None else: nums = nums[-k:]+nums[:-k] return (nums)
I have the same problem at first. Then i changed the 'nums' into 'nums[:]'. It was accpeted. I guess it is because it requires '# @return nothing, please modify the nums list in-place.'
def rotate(self, nums, k):
nums[:] = nums[len(nums)-k:]+nums[:len(nums)-k]
you can revise nums=nums[-k:]+nums[:-k] into nums[:]=nums[-k:]+nums[:-k] ,then it'll work
Hi @Krystal - I see this works ; but what is the difference between the two usages .
+1 this question -- Can anyone explain what the '[:]' syntax means and why it might make a difference here?
assume you call the function like below:
a = [1,2,3,4,5,6]
In the rotate function, variable nums is not a list ,
it's a reference of list a
nums[:] = [1,2,3] operating will edit the list as a references (they share same memory area)
nums= [1,2,3], you just give the reference of [1,2,3] to nums, after this nums doesn't reference the old list (a) any more
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.