leetcode day10 Rotate Array

题目:给一个数组,给定一个k,数组k steps向后移动,你知道的就是这样:
在这里插入图片描述
思路:
1、暴力倾向的我们总是不同意的你知道吧
然后是参考答案给出来的:
2、利用额外的数组进行辅助计算:

class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        a_list = list(nums)
        i_k = i = 0
        length = len(nums)
        while i_k < length:
            a_list[(i_k+k)%length] = nums[i_k]
            i_k += 1
        while i < length:
            nums[i] = a_list[i]
            i += 1

3、reverse:
在这里插入图片描述

class Solution(object):
    def rotate(self, nums, k):
        k %= len(nums)
        self.reverse(0, len(nums)-1, nums)
        self.reverse(0, k-1, nums)
        self.reverse(k, len(nums)-1, nums)
    def reverse(self, start, end, nums):
        while (start < end):
            tmp = nums[start]
            nums[start] = nums[end]
            nums[end] = tmp
            start += 1
            end -= 1

利用python自身的性质:
3、前k项与后k项相交换:

class Solution:
    # @param nums, a list of integer
    # @param k, num of steps
    # @return nothing, please modify the nums list in-place.
    def rotate(self, nums, k):
        n = len(nums)
        k = k % n
        nums[:] = nums[n-k:] + nums[:n-k]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值