标签:
leetcode - 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.
Related problem: Reverse Words in a String II
1 class Solution { 2 public: 3 void rotate(vector<int>& nums, int k) { 4 vector<int> res; 5 //vector<int>::iterator it1 = nums.begin(); 6 if(k==0) return; 7 vector<int>::iterator it2 = nums.begin() + (nums.size() - k%nums.size()); 8 vector<int>::iterator it = it2; 9 while(it!=nums.end()){ 10 res.push_back(*it); 11 it++; 12 } 13 it = nums.begin(); 14 while(it!= it2){ 15 res.push_back(*it); 16 it++; 17 } 18 nums = res; 19 } 20 };
然而这个方法空间复杂度为n,还有一种空间复杂度为1的版本:
class Solution { public: void rotate(int nums[], int n, int k) { k = k % n; reverse(nums, nums + n); reverse(nums, nums + k); reverse(nums + k, nums + n); } };
先把AB reverse一次得到reverse(B)reverse(A)
然后再把reverse(B),reverse(A)分别reverse一次就得到了BA
很巧妙。
标签:
原文地址:http://www.cnblogs.com/shnj/p/4501001.html