LeetCode 189.
Tags: LeetCode
Intuition
keep a subarray of right side of array and replace right side of it by left side. After that, replace the other side.
Approach
- create a subarray which size is equal to k to keep the right side of array
- replace right side by left side first
- then replace left side by right side
Complexity
-
Time complexity: O(n)
-
Space complexity: O(k)
Code
class Solution {
public void rotate(int[] nums, int k) {
k = k % nums.length;
int[] tmp = new int[k];
for (int i=nums.length-k; i<nums.length; i++) {
tmp[i + k - nums.length] = nums[i];
}
for (int i=nums.length-k-1; i>=0; i--) {
nums[i + k] = nums[i];
}
for (int i=0; i<k; i++) {
nums[i] = tmp[i];
}
}
}
Check out the description of this problem at LC 189.