Skip to content

Commit a379459

Browse files
Create 0189. Rotate Array.md
1 parent 4df7324 commit a379459

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

JS-Algo/0189. Rotate Array.md

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<img width="674" alt="Screenshot 2024-03-27 at 11 55 18 PM" src="https://github.com/cheatsheet1999/FrontEndCollection/assets/37787994/c4e36b69-b836-4a8e-8322-8eba09b9ddb8">
2+
3+
4+
```js
5+
/**
6+
* @param {number[]} nums
7+
* @param {number} k
8+
* @return {void} Do not return anything, modify nums in-place instead.
9+
*/
10+
var rotate = function(nums, k) {
11+
function swap(i, j) {
12+
while(i < j) {
13+
[nums[i], nums[j]] = [nums[j], nums[i]];
14+
i++;
15+
j--;
16+
}
17+
}
18+
19+
k %= nums.length;
20+
// 7 6 5 4 3 2 1
21+
swap(0, nums.length - 1);
22+
// 5 6 7 4 3 2 1
23+
swap(0, k - 1);
24+
// 5 6 7 1 2 3 4
25+
swap(k, nums.length - 1);
26+
};
27+
```

0 commit comments

Comments
 (0)