189. rotate array

Given an array, rotate the array to the right by k steps, where k is non-negative. 给定一个数组,将数组向右旋转k步,其中k为非负数。

Example 1:

Input: [1,2,3,4,5,6,7] and k = 3

Output: [5,6,7,1,2,3,4]

Explanation:

rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]

Example 2:

Input: [-1,-100,3,99] and k = 2

Output: [3,99,-1,-100]

Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]

Note:

Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space? 尝试尽可能多地提出解决方案,至少有3种不同的方法可以解决这个问题。 你能用O(1)额外空间就地做到吗?

思路:

  • 使用额外的空间, 一个用队列进行存储,另一个使用栈进行存储
  • 使用字符串的截取功能,将后面的字符串直接拼接到原字符串前面
  • 也等价于将头部加到字符串的尾部
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.
        """
        l = nums[:len(nums) - k]
        l2 = nums[len(nums) - k:len(nums)]
        nums = l2 + l
        print(nums)
        # print(l)

if __name__ == "__main__":
    n = [1, 2, 3, 4, 5, 6, 7]
    k = 3
    Solution().rotate(n, k)

此方法出错,原因不知 — layout: post title: “189. Rotate Array” tag: leetcode刷题笔记 —

网上思路: https://blog.csdn.net/coder_orz/article/details/52052767

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.
        """
        #重新赋值
        k = k % len(nums)
        nums[:k] = nums[len(nums)-k:]
        nums[k:] = nums[:len(nums) - k]
        print(nums)

if __name__ == "__main__":
    n = [1, 2, 3, 4, 5, 6, 7]
    k = 3
    Solution().rotate(n, k)

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦