def rotate(self, nums, k): if len(nums)>1: temp_list= for i in range(len(nums)): if i<k: temp_list.append(nums[i]) new_num=nums[k:]+temp_list nums=new_num
This works in my own program. I know it's not the most efficient way to code, but it should work.
However, what should be [2,1] from [1,2],1 returns [1,2] on OJ. WHY!?!?!?!?!?
Okay, after digging some of the discussion threads, I know what happened
still not sure why 'nums' and 'nums[:]' makes a difference though
Well , I m running into a similar problem ( could be the same too ) . If I run it on my computer - it seems to work , but not on the OJ
[1,2],1 ===> the same program returns [2,1] on my mac
[1,2],1 ===> returns [1,2] on OJ
I had the same issue (returned [2,1] on my computer but [1,2] in the OJ), and fixed the problem by setting nums[:] = new_num instead of nums = new_num (my code was slightly different, but what's important is that you reset nums[:] at the end rather than nums). Can anyone explain what the '[:]' syntax means and why it might make a difference here?
If you only use nums=new_num, you just chance the reference of nums to new_num, but only inside your function. The original nums stays the same. So nums[:] might refer to the content of the list instead of it's reference.
here's my code, that changes the original list:
def rotate(self, nums, k): if len(nums) != 1 and k != 0: for i in range(k): nums.insert(0,nums.pop())
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.