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.
思路:
需要一个临时数组储存原数据,然后先取后k个元素放到结果数组前边,再将原数据其余元素放到结果数组后边。
void rotate(vector<int>& nums, int k) { if (k <= 0 || k%nums.size() == 0)return; vector<int>temp = nums; int size = nums.size(); k %=size; int i = 0; for (int j = size - k; i < k;j++) { nums[i++] = temp[j]; } for (int j = 0; j < size - k;j++) { nums[i++] = temp[j]; } }