[leetcode]旋转数组

题目描述:

给定一个数组,将数组中的元素向右移动 个位置,其中 是非负数。

示例 1:

输入: [1,2,3,4,5,6,7]k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右旋转 1 步: [7,1,2,3,4,5,6]
向右旋转 2 步: [6,7,1,2,3,4,5]
向右旋转 3 步: [5,6,7,1,2,3,4]

示例 2:

输入: [-1,-100,3,99]k = 2
输出: [3,99,-1,-100]
解释: 
向右旋转 1 步: [99,-1,-100,3]
向右旋转 2 步: [3,99,-1,-100]

说明:

  • 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
  • 要求使用空间复杂度为 O(1) 的原地算法。

题目分析:

列表的分片操作

# !/usr/bin/env python
# _*_  coding: utf-8 _*_


class Solution():
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums_len = len(nums)
        nums[:] = nums[nums_len - k :] + nums[:nums_len - k]


if __name__ == '__main__':
    test_nums1 = [-1, -100, 3, 99]
    test_nums2 = [1, 2, 3, 4, 5, 6, 7]

    my_solution = Solution()
    my_solution.rotate(test_nums1, 2)
    my_solution.rotate(test_nums2, 3)
    print(test_nums1)
    print(test_nums2)

猜你喜欢

转载自www.cnblogs.com/ralap7/p/9019021.html