登录
  • #刷题

加米‌‌‍‍‌‍‌‌‌‌‍‍‌‍‌‍‍‍‌‌‌‌‌‌‌‌‍‌‌‍‍‌,请大家帮看一下189. Rotate Array, python里pass by reference的细节

超人96825
157
6
大家好

题目lc189,rotate array有一点python 3细节上的疑问,请大家帮忙看看,会尽力加米。
Given an array, rotate the array to the right by k steps, where k is non-negative.[br][/br][br][/br]Example 1:[br][/br][br][/br]Input: nums = [1,2,3,4,5,6,7], k = 3[br][/br][br][/br]Output: [5,6,7,1,2,3,4][br][/br][br][/br]Explanation:[br][/br][br][/br]rotate 1 steps to the right: [7,1,2,3,4,5,6][br][/br][br][/br]rotate 2 steps to the right: [6,7,1,2,3,4,5][br][/br][br][/br]rotate 3 steps to the right: [5,6,7,1,2,3,4]
我的答案和思路:

将给定list全部reverse一遍,再分别reverse前k个数,后(n-k)个数,就达到了分段rotate的目的。

我的问题,这段代码运行出来

Solution.rotate([1,2,3,4,5,6], 3) 结果是[6,5,4,3,2,1]。debug发现self.reverse(nums[​:k]), self.reverse(nums[k:])运行后,nums不会发生改变。nums是mutable param, 传入function的param的改变不是应该同步吗?而且为什么self.reverse(nums)就可以实现nums的内容update?
class wrong_Solution:[br][/br][br][/br]    def rotate(self, nums: List[int], k: int) -> None:[br][/br][br][/br]    """[br][/br][br][/br]    Do not return anything, modify nums in-place instead.[br][/br][br][/br]    """[br][/br][br][/br]        self.reverse(nums)[br][/br][br][/br]        self.reverse(nums[​:k])[br][/br][br][/br]        self.reverse(nums[k:])[br][/br][br][/br]        [br][/br][br][/br]    def reverse(self, nums):[br][/br][br][/br]        left, right = 0, len(nums) - 1[br][/br][br][/br]        while left <= right:[br][/br][br][/br]            nums[left], nums[right] = nums[right], nums[left][br][/br][br][/br]            left += 1[br][/br][br][/br]            right -= 1[code]right solution[br][/br][br][/br]class Solution:[br][/br][br][/br]    # I Love Yahoo solution; O(n) O(1)[br][/br][br][/br]    def reverse(self, nums: list, start: int, end: int) -> None:[br][/br][br][/br]        while start < end:[br][/br][br][/br]            nums[start], nums[end] = nums[end], nums[start][br][/br][br][/br]            start, end = start + 1, end - 1[br][/br][br][/br]    def rotate(self, nums: List[int], k: int) -> None:[br][/br][br][/br]        #ATTENTION: without L12, l16 would return out of range error.[br][/br][br][/br]        n = len(nums)[br][/br][br][/br]        k %= n[br][/br][br][/br]        self.reverse(nums, 0, n - 1)[br][/br][br][/br]        self.reverse(nums, 0, k - 1)[br][/br][br][/br]        self.reverse(nums, k, n - 1)[br][/br][br][/br][/code][/right][/right]
6条回复
热度排序

发表回复