旋转数组
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
代码:
思路:
我的思路涉及三个知识点。
1.Python 中, list 相加指的是列表相加,而不是列表中的每个值相加。
区分字符串相加 + ,extend() ,前者是生成一个新的对象,后者是原地修改对象。
注意元素添加 append()。
https://blog.csdn.net/weixin_42350212/article/details/80628539
2.深入理解python切片操作
切片操作提供三个参数[start_index,stop_index,step]
start_index是切片的起始位置
stop_index是切片的结束位置(不包括)
step可以不提供,默认值是1,步长值不能为0,不然会报错ValueError
https://blog.csdn.net/xpresslink/article/details/77727507
3.list 赋值时,l1=l 与 l1=l[:]区别
前者是对对象的引用,后者是直接创建了一个新的对象(指向了新的地址)
https://www.zhihu.com/question/54282837
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. """ n = len(nums) nums[:] = nums[n-k:] + nums[:n-k]