Skip to content

Commit b65a543

Browse files
authored
Time complexity: O(N) Space complexity: O(N)
Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: nums = [1,2,3,4,5,6,7], 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: nums = [-1,-100,3,99], 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]
1 parent 9e03d0f commit b65a543

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

0189. Rotate Array

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public void rotate(int[] nums, int k) {
3+
k %= nums.length;
4+
reverse(nums, 0, nums.length - 1);
5+
reverse(nums, 0, k - 1);
6+
reverse(nums, k, nums.length - 1);
7+
}
8+
9+
public void reverse(int[] nums, int start, int end) {
10+
while (start < end) {
11+
int temp = nums[start];
12+
nums[start] = nums[end];
13+
nums[end] = temp;
14+
start++;
15+
end--;
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)