Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
Input: [1,2,3,4,5,6,7]
and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99]
and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Note:
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
- Could you do it in-place with O(1) extra space?
题目的解释中已经给的很清楚,在这里提供三种解法,其中第一和第二种算法Accept,第三种由于占用空间过多无法通过,写一下提供参考。
法一:用栈的思维,先进后出,后出前进,调用C++自带函数,可以很简单的实现算法,该方法Accept。
1 void rotate(vector<int>&nums, int k) 2 { 3 int size = nums.size(); 4 int record; 5 int counter = k; 6 while (counter>0) 7 { 8 record = nums[size - 1]; 9 nums.pop_back(); 10 nums.insert(nums.begin(), record); 11 counter--; 12 } 13 }
法二:利用取余规律进行数组数据按要求重排,方法简单,Accept。1 void rotate(vector<int>&nums, int k) 2 { 3 if (nums.size() == 0 || k <= 0)return; 4 vector<int> space(nums); 5 for (int i = 0; i<nums.size(); i++) 6 nums[(i + k) % nums.size()] = space[i]; 7 }
法三:严格按照Explanation中的步骤一步步执行,消耗空间多,无法Accept。
1 void rotate(vector<int>nums, int k) //时间复杂度较高,LeetCode无法通过 2 { 3 int size = nums.size(); 4 int record; 5 int counter = k; 6 while (counter>0) 7 { 8 record = nums[size-1]; 9 for (int j = size - 1; j > 0; --j) 10 { 11 nums[j] = nums[j-1]; 12 } 13 nums[0] = record; 14 counter--; 15 } 16 }