---
# System prepended metadata

title: 'LeetCode #189 [Rotate Array](https://leetcode.com/problems/rotate-array)'
tags: [LeetCode, Medium]

---

###### tags: `LeetCode` `Medium`
# LeetCode #189 [Rotate Array](https://leetcode.com/problems/rotate-array)
### (Medium)
給定一個數組，將數組中的元素向右移動 k 個位置，其中 k 是非負數。
Ex: nums=[1,2,3,4,5,6,7], k=3, 則轉換完的答案為[5,6,7,1,2,3,4]


---
做三次反轉:
1. 全vector反轉, 得到[7,6,5,4,3,2,1]
2. 前k項反轉, 得到[5,6,7,4,3,2,1]
3. 後nums.size()-k項反轉, 得到[5,6,7,1,2,3,4]即為答案


---
```
class Solution {
public:
    void rotate(vector<int>& nums, int k) {
        k=k%nums.size();
        reverse(nums.begin(),nums.end());
        reverse(nums.begin(),nums.begin()+k);
        reverse(nums.begin()+k,nums.end());
    }
};
```