1-3旋转数组

JAVA

class Solution {
    public void rotate(int[] nums, int k) {
        k = k%nums.length;
        int count = 0;
        for (int start = 0; count < nums.length; start++){
            int current = start;
            int prev = nums[start];
            do{
                int next = (current+k)%nums.length;
                int temp = nums[next];
                nums[next] = prev;
                prev = temp;
                current = next;
                count++;                
            }while(start != current);
        }
    }
}

python

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        l = len(nums)
        nums[0:k], nums[k:] =  nums[l-k:], nums[0:l-k]

你可能感兴趣的:(1-3旋转数组)