Title: Rotating an Array
- Problem Description:
Rotate an array of n elements to the right by k steps.
For example, if n = 7 , k = 3, given the array [1,2,3,4,5,6,7], the result after right rotation is [5,6,7,1,2,3, 4].
Hint:
The required space complexity is O(1)
C++:
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if(nums.empty()||(k%=nums.size())==0)
return ;
int n = nums.size();
for(int i = 0;i<n-k;++i)
{
nums.push_back(nums[0]); //将原数组中第一个数字插入到数组末尾
nums.erase(nums.begin()); //将原数组中第一个数字删除
}
}
};