前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q189 Rotate Array

Q189 Rotate Array

作者头像
echobingo
发布2018-04-25 16:58:00
4860
发布2018-04-25 16:58:00
举报

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

解题思路:

此题不难,这里给出两种方法:

方法1:列表元素从后向前,一个个取出,不断插入最前面,插入 k 个即可。见 Python 实现 rotate 函数。

方法2:使用Python的切片,把后k个元素放到前面即可。见 Python 实现 rotate2 函数。

注意点:

将一个列表(如 a = [1,2,3])作为参数传入函数,如果在函数中执行 a = [4,5,6], a会在函数中改变,但是出了函数 a并没有改变(还是 [1,2,3])。如果想要 a 出了函数也改变,应该使用 a[:] = [4,5,6]。

Python实现1:
代码语言:javascript
复制
class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        n = len(nums) - 1
        while k > 0:
            num = nums.pop()
            nums.insert(0, num)
            n -= 1; k-= 1
        # return nums

    def rotate2(self, nums, k):
        n = len(nums) - k
        # 注意,应该使用 nums[:] 而不是 nums,前者可以真正改变传入的nums列表,而后者不可以
        nums[:] = nums[n:] + nums[:n]  
        # return nums

a = [1,2,3,4,5,6,7]
k = 3
b = Solution()
print(b.rotate(a[:], k))  # [5,6,7,1,2,3,4]
print(b.rotate2(a, k)) # [5,6,7,1,2,3,4]
print(a) # [5,6,7,1,2,3,4]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • 注意点:
  • Python实现1:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档