敝人要問的是這題:
https://leetcode.com/problems/rotate-array/
使用以下解法
nums = nums[len(nums)-k:] + nums[:len(nums)-k]
卻顯示nums不變
必須使用shallow copy才能AC
nums[:] = nums[len(nums)-k:] + nums[:len(nums)-k]
小弟實在不懂,為何需使用shallow copy後才能修改到nums
在此先謝謝各位,如果題目描述得不夠清楚,本人會再補充
你在 LeetCode 的發問
已經有人回答你了
差別在於有沒有寫[:] 決定會不會改到原本的值
以下是範例程式
應該可以看出其差別
結論是#2 在 rotate 裡有改變 nums,不會影響到主程式裡的 nums
#3 在 rotate 裡有改變 nums[:],會修改到主程式裡的 nums
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
print(" >>>>> in class >>>>>")
print(nums)
nums = nums[len(nums)-k:] + nums[:len(nums)-k]
print(nums)
print(" >>>>> in class >>>>>")
def rotateByRef(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
print(" >>>>> in class >>>>>")
print(nums)
nums[:] = nums[len(nums)-k:] + nums[:len(nums)-k]
print(nums)
print(" >>>>> in class >>>>>")
k = 3
"""#1 Use variable directly"""
print("#1 ===============")
nums = [1,2,3,4,5,6,7]
print(nums)
nums = nums[len(nums)-k:] + nums[:len(nums)-k]
print(nums)
"""#2 Class method by Value"""
nums = [1,2,3,4,5,6,7]
print("#2 ===============")
print(nums)
me = Solution()
me.rotate(nums, k)
print(nums)
"""#3 Class method by Reference"""
nums = [1,2,3,4,5,6,7]
print("#3 ===============")
print(nums)
me = Solution()
me.rotateByRef(nums, k)
print(nums)
右旋
nums = nums[-1:] + nums[:len(nums)-1]
左旋
nums = nums[1:] + nums[0:1]
Japhen Chen你好
本人的問題在於,為何該題需使用nums[:] = nums[len(nums)-k:] + nums[:len(nums)-k]才能通過,而不是nums = nums[len(nums)-k:] + nums[:len(nums)-k]