LeetCode/solutions/189. Rotate Array.md
2019-09-13 23:08:41 +08:00

22 lines
792 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [189. Rotate Array](https://leetcode.com/problems/rotate-array/description/)
# 思路
题意就是循环右移k步如果仔细观察结果可知结果相当于先对数组整体进行翻转再对前k个元素和后面的元素分别进行翻转的结果。
例如[1,2,3,4,5,6,7], k = 3:
先整体翻转:[7,6,5,4,3,2,1];
再对前3个元素翻转:[5,6,7,4,3,2,1];
再对后面的元素翻转:【5,6,7,1,2,3,4]。
时间复杂度O(n), 空间复杂度O(1)。
# C++
``` C++
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k %= nums.size(); // 注意先取模
if(k == 0) return;
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}
};
```