---
# System prepended metadata

title: 189. Rotate Array
tags: [leetcode, array]

---

# 189. Rotate Array

題目：<https://leetcode.com/problems/rotate-array/>

解法：首先此動作是循環的，所以 k 先 mod 陣列長度，就可以確定最少移動步數，接著由於陣列長度可能很大，所以採每個元素依序移動的方式，先暫存目前值，移動到目標位置，再暫存目標位置的值，將前一個暫存值置入陣列目標位置後，再重複執行，若目標位置回到起始位置，則起始位置加1，直到所有以替換所有元素。

Python3：

``` python 3
class Solution:
    def rotate(self, nums: list[int], k: int) -> None:
        length = len(nums)
        k %= length
        if k == 0 or k == length:
            return
        idx = start = 0
        prev = nums[idx]
        count = 0
        while count < length:
            idx = (idx + k) % length
            tmp = nums[idx]
            nums[idx] = prev
            prev = tmp
            count += 1
            if start == idx:
                start += 1
                idx = start
                prev = nums[idx]

if __name__ == '__main__':
    nums = [1, 2, 3, 4, 5, 6, 7]
    k = 3

    Solution().rotate(nums, k)
    print(nums)
```

C：

``` c
#include <stdio.h>
#include <stdlib.h>

void rotate(int* nums, int numsSize, int k) {
    k %= numsSize;
    if (k == 0 || k == numsSize)
        return;
    int start, idx, prev, count;
    idx = start = 0;
    prev = nums[idx];
    count = 0;
    while (count < numsSize) {
        idx = (idx + k) % numsSize;
        int tmp = nums[idx];
        nums[idx] = prev;
        prev = tmp;
        count++;
        if (start == idx) {
            start++;
            idx = start;
            prev = nums[idx];
        }
    }
}

int main() {
    int nums[] = {1, 2, 3, 4, 5, 6, 7};
    int numsSize = sizeof(nums) / sizeof(nums[0]);
    int k = 3;
    
    rotate(nums, numsSize, k);
    for (int i = 0; i < numsSize; i++)
        printf("%d\n", nums[i]);
    return 0;
}
```

###### tags: `leetcode` `array`
