Original title:
Given an array, the array elements to the right k positions, wherein 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 right Step 1:[7,1,2,3,4,5,6]
rotates two steps to the right:[6,7,1,2,3,4,5]
rotation to the right Step 3:[5,6,7,1,2,3,4]
Example 2:
Input: [-1,-100,3,99]
and K 2 =
Output: [3,99, -1, -100]
Explanation:
rotation to the right Step 1: [99, -1, -100,3]
Rotate Right Step 2: [3.99, - 1 -100]
Description:
- As far as possible to come up with more solutions, there are at least three different ways to solve this problem.
- It requires space complexity is O (1) algorithm situ.
Ideas: the class talked about, a first anti, anti again one last time and then trans.
Nk digits before the first flip, then after k numbers flip it, flip it and finally the entire array:
1 2 3 4 5 6 7
4 3 2 1 5 6 7
4 3 2 1 7 6 5
5 6 7 1 2 3 4
class Solution { public: void rotate(vector<int>& nums, int k) { int len = nums.size(); if (len==1||k==0) { return ; } k=k % len; int n = nums.size(); reverse(nums.begin(), nums.end()-k); reverse(nums.begin() + n - k, nums.end()); reverse(nums.begin(), nums.end()); } };