189. Rotate Array刷题笔记

运行报错可能是因为不是原地置换数组

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        for _ in range(k):
            tmp = nums.pop()
            nums = [tmp] + nums

用mod解决该问题
但是这种方法只能解决互质和恰为倍数的情况

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if k == 0:
            return
        n = len(nums)
       
        if len(nums)%k:
            pos = 0
            tmp = nums[0]
            for _ in range(n):
                npos = (pos+k)%n
                tmp1 = nums[npos]
                nums[npos] = tmp
                tmp = tmp1
                pos = npos
                print(nums)
        else:
            t = len(nums)//k
            for pos in range(k):
                tmp = nums[pos]             
                for _ in range(t):
                    npos = (pos+k)%n
                    tmp1 = nums[npos]
                    nums[npos] = tmp
                    tmp = tmp1
                    pos = npos

其实可以用三次颠倒来解决,加上取模和剪枝判断

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        def reverse(i,j):
            while i<j:
                nums[i],nums[j] = nums[j],nums[i]
                i += 1
                j -= 1
        n = len(nums)
        if n<=1:
            return
        k = k%n
        if k == 0:
            return
        reverse(0,n-1)
        reverse(0,k-1)
        reverse(k,n-1)

你可能感兴趣的:(LeetCode,Python刷题,leetcode,算法,职场和发展)