Share my simple python solution (beats 79.85%)


  • -1
    E
    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.
        """
        n=len(nums)
        if n==1:
            return
        if k>0:
            if k>n:
                k=k%n
            if k==n or k==0:
                return
            nums[:k],nums[k:]=nums[-k:],nums[:-k]
            return
        elif k<0:
            k=-k
            if k>n:
                k=k%n
            if k==n or k==0:
                return
            nums[:-k],nums[-k:]=nums[k:],nums[:k]

  • -1
    Y

    a better solution is:

    def rotate(self, nums, k):
            n = len(nums)
            k = abs(k)
            k = k%n
            if k!=0:
                nums[k:], nums[:k]= nums[:-k] , nums[-k:]
    

  • 0
    E

    Yes, you are right. I did not notice they were actually the same. Thank you!


  • 0

    actually, in the run-time, the space will be consumed O(n) because nums[:] will get a copy of nums in certain range.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.