首页 > 代码库 > 189. Rotate Array
189. Rotate Array
1. 问题描述
189. Rotate Array
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Hint:
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Tags: Array
Similar Problems: (M) Rotate List (M) Reverse Words in a String II
2. 解题思路
3. 代码
#include <algorithm>class Solution {public: void rotate_1(vector<int>& nums, int k) { int vSize = nums.size(); k = k % vSize; for (int i=0; i<vSize/2; i++) { int t = nums[i]; nums[i] = nums[vSize-1-i]; nums[vSize-1-i] = t; } for (int i=0; i<k/2; i++) { int t = nums[i]; nums[i] = nums[k-1-i]; nums[k-1-i] = t; } for (int i=k; i<k + (vSize-k)/2; i++) { int t = nums[i]; nums[i] = nums[vSize-1-i+k]; nums[vSize-1-i+k] = t; } } void rotate_2(vector<int>& nums, int k)//使用reverse()函数需引入#include <algorithm> { k = k % nums.size(); reverse(nums.begin(), nums.end()); reverse(nums.begin(), nums.begin()+k); reverse(nums.begin()+k, nums.end()); }};
4. 反思
189. Rotate Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。