旋转数组

2019-06-18  本文已影响0人  HaiYi_

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

示例 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]

解法一:

class Solution:
    def rotate(self, nums, k):
        k = k % len(nums)
        nums[:] = nums[-k:] + nums[:-k]
        print(nums)

        
if __name__ == '__main__':
    lsi = [1, 2, 3, 4, 5]
    S = Solution()
    s = S.rotate(lsi, 3)
    print(s)

解法二:

class Solution:
    def rotate(self, nums, k):
        k = k % len(nums)
        while k > 0:
            nums.insert(0, nums[-1])
            nums.pop()
            k -= 1
        return nums


if __name__ == '__main__':
    lsi = [1, 2, 3, 4, 5]
    S = Solution()
    s = S.rotate(lsi, 3)
    print(s)

解法三:

class Solution:
    def rotate(self, nums, k):
        k = k % len(nums)
        numss = nums[:]
        l = len(nums)
        for i in range(l):
            nums[(i + k) % l] = numss[i]
        return nums


if __name__ == '__main__':
    lsi = [1, 2, 3, 4, 5, 6, 7]
    S = Solution()
    s = S.rotate(lsi, 3)
    print(s)

上一篇下一篇

猜你喜欢

热点阅读