0

## Leetcode 189題 Rotate Array（用Python）

nums = nums[len(nums)-k:] + nums[:len(nums)-k]

nums[:] = nums[len(nums)-k:] + nums[:len(nums)-k]

### 2 個回答

0

iT邦大神 1 級 ‧ 2020-10-27 11:15:21

`#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)
``````
ffaanngg iT邦新手 5 級 ‧ 2020-10-27 12:58:04 檢舉

0
japhenchen
iT邦大師 1 級 ‧ 2020-10-26 10:37:41

``````nums = nums[-1:] + nums[:len(nums)-1]
``````

``````nums = nums[1:] + nums[0:1]
``````

ffaanngg iT邦新手 5 級 ‧ 2020-10-26 10:55:48 檢舉

Japhen Chen你好

array只有一維，或二維以上但沒有可變型態的值的情況下，就只要用shallow copy即可

ffaanngg iT邦新手 5 級 ‧ 2020-10-26 15:48:47 檢舉