- 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?
Could you do it in-place with O(1) extra space?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
- Total Accepted: 79153
- Total Submissions:362634
- Difficulty: Easy
思考:1.k%n,当k=n时,相当于没有旋转,这样可以处理一些情形2.旋转等效于:拿在后面的k个数据与前n-k个数据交换位置,并且两块里面的元素的相对位置不改变3.考虑k小于n/2还是大于n/24.感觉使用memecpy估计是最快的,直接复制内存内容方法1class Solution { public: void rotate(vector<int>& nums, int k) { int s = nums.size(); k = k%s; if (k <= s / 2)//把后面的移动到前面 { for (int i = 0; i <k; i++) { nums.insert(nums.begin(), nums[nums.size() - 1]); nums.pop_back(); } } else//把前面的移动到后面 { for (int i = 0; i<s-k; i++) { nums.push_back(nums[0]); nums.erase(nums.begin()); } } } };
方法2:void rotate(int nums[], int n, int k) { k = k % n; if (k == 0) return; int *temp = new int[n]; memcpy(temp, nums+(n-k), sizeof(int)*k); memcpy(temp+k, nums, sizeof(int)*(n-k)); memcpy(nums, temp, sizeof(int)*n); delete[] temp; }
方法3:
class Solution { public: void rotate(vector<int>& nums, int k) { int s = nums.size(); k = k%s; reverse(nums.begin(), nums.begin() + s - k); reverse(nums.begin()+s-k, nums.begin() + s); reverse(nums.begin(), nums.begin() + s); } };
- Total Accepted: 79153
- Total Submissions:362634
- Difficulty: Easy