Given an array of integers nums, rotate it k times to its right, in place, using O(1) extra memory.
One rotation to the right moves every number one position to the right, and the last number moves to the front.
Your function rearranges the numbers inside nums itself, without building a new array: the output in the examples is nums after the call. (In Rust the function takes nums by value, so it returns that same vector, rotated.)
Example 1:
Input: nums = [1, 2, 3, 4, 5], k = 2 Output: [4, 5, 1, 2, 3] Explanation: After 1 rotation: [5, 1, 2, 3, 4]. After 2 rotations: [4, 5, 1, 2, 3].
Example 2:
Input: nums = [1, 2, 3, 4, 5, 6, 7, 8], k = 3 Output: [6, 7, 8, 1, 2, 3, 4, 5]
Constraints:
1 <= nums.length <= 3 * 1041 <= nums[i] <= 231 - 11 <= k <= nums.length
Your algorithm should run in O(n) time and use O(1) extra space.
Free plan: 30 tutor messages. PRO is unlimited.
