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]
- code
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, nums.length - 1);
}
public void reverse(int[] nums, int start, int end){
while (start < end){
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
- code
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k %= n
start = count = 0
while count < n:
current = start
while True:
next_idx = (current + k) % n
nums[next_idx], nums[start] = nums[start], nums[next_idx]
current = next_idx
count += 1
if start == current:
break
start += 1
c2, either use -k or use n-k, don’t use both like n[-k:] + n[:n-k], will get [1,1] when [1]
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k%n
head = n - k
nums[:] = nums[head:] + nums[:head]
code,
k = k % len(nums)
# use -k or use len(nums)-k, can't use both in a same line.
nums[:] = nums[-k:] + nums[:-k]```