# Leetcode 189. Rotate Array 練習
> Difficulty : `Medium`
> `Java` `演算法Algorithm`
> 撰寫人[name=KVJK_2125] [time=Fri, Mar 29, 2024 16:00]
## 題目
### 說明 Description
原文:`Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.`
翻譯:給一個整數陣列nums,將陣列中的元素循環右移 k 個位置,其中 k 非負數。
### 範例 Example
Example 1:
> Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
>Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
>Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
>Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
### 限制條件 Constraints
- `1 <= nums.length <= 105`
- `-231 <= nums[i] <= 231 - 1`
- `0 <= k <= 105`
## 解題
### 思路 Intuition/Approach
- Step1.<br> 如果k=3,則陣列內nums[0]的執會成為輸出陣列的[3]
- Step2.<br> 如下圖推算<br>
- Step3.<br> 更改移動位置時,可以發現`(k+原位置)%nums.length`滿足移動後位置的條件
### 程式碼 Code(加註解)
```clink=java
class Solution {
public void rotate(int[] nums, int k) {
//建立一個空陣列儲存結果
int cut[] = new int[nums.length];
//把題目提供的陣列提供到新陣列的位置
for(int i = 0; i < nums.length; i++)
cut[(k + i) % nums.length] = nums[i];
//把移動過的新陣列放回原本的陣列
for(int i = 0; i < nums.length; i ++)
nums[i] = cut[i];
}
}
```