-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path189-rotate_array.js
More file actions
39 lines (35 loc) · 952 Bytes
/
189-rotate_array.js
File metadata and controls
39 lines (35 loc) · 952 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Given an array, rotate the array to the right by k steps, where k is non-negative.
* 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]
*/
/**
*
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
/*
Approach: Using Reverse
Time complexity: O(n) . n elements are reversed a total of three times.
Space complexity: O(1) . No extra space is used
*/
const revNums = (nums, start, end) => {
while (start < end) {
[nums[start], nums[end]] = [nums[end], nums[start]];
start++;
end--;
}
};
var rotate = function (nums, k) {
k = k % nums.length;
nums.reverse();
revNums(nums, 0, k - 1);
revNums(nums, k, nums.length - 1);
console.log(nums);
};
rotate([1, 2, 3, 4, 5, 6, 7], 3);