LeetCode 189 [Rotate Array]

作者: Jason_Yuan | 来源:发表于2016-08-01 17:24 被阅读15次

原题

给出一个n个元素的数组,向右位移k位。比如 n = 7 and k = 3, 已知数组为[1,2,3,4,5,6,7] 旋转之后为 [5,6,7,1,2,3,4].

解题思路

  • 跟LintCode中旋转string是一样的思路,三步翻转法

完整代码

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.
        """
        if len(nums) == 0:
            return
        k %= len(nums)
        self.helper(nums, len(nums) - k, len(nums) - 1)
        self.helper(nums, 0, len(nums) - k - 1)
        self.helper(nums, 0, len(nums) - 1)
        
    def helper(self, nums, i, j):
        while i < j:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1
            j -= 1

相关文章

网友评论

    本文标题:LeetCode 189 [Rotate Array]

    本文链接:https://www.haomeiwen.com/subject/hozxsttx.html