-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0189-rotate-array.js
64 lines (56 loc) · 1.26 KB
/
0189-rotate-array.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Two Pointers
* https://leetcode.com/problems/rotate-array/
*
* Time O(n) | Space O(1)
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
// if the k exceeds the length of nums.
k = k % nums.length;
nums.reverse();
reversePortionOfArray(nums, 0, k - 1);
reversePortionOfArray(nums,k, nums.length - 1);
};
var reversePortionOfArray = function(nums,start,end) {
while(start < end) {
[nums[start],nums[end]] = [nums[end],nums[start]];
start++;
end--;
}
}
/**
* Two Pointers
* https://leetcode.com/problems/rotate-array/
*
* Time O(n) | Space O(1)
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
var rotate = function(nums, k) {
k = k % nums.length;
let l = 0;
let r = nums.length - 1;
while (l < r) {
[nums[l], nums[r]] = [nums[r], nums[l]];
l += 1;
r -= 1;
}
l = 0,
r = k - 1;
while (l < r) {
[nums[l], nums[r]] = [nums[r], nums[l]];
l += 1;
r -= 1;
}
l = k;
r = nums.length - 1;
while (l < r) {
[nums[l], nums[r]] = [nums[r], nums[l]];
l += 1;
r -= 1;
}
};