-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsolution-pointer.ts
More file actions
43 lines (33 loc) · 795 Bytes
/
solution-pointer.ts
File metadata and controls
43 lines (33 loc) · 795 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
40
41
42
43
/*
* @lc app=leetcode id=189 lang=javascript
*
* [189] Rotate Array
*/
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/
const rotate = (nums: number[], k: number): void => {
const len = nums.length;
k = k % len;
if (len < 2 && k == 0) return;
let writeCount = 0;
let subLoopStartIndex = 0;
while (writeCount < len) {
let p = subLoopStartIndex;
let cacheItem = nums[p];
do {
const nextIndex = (p + k) % len;
// * jump, write, cache
const temp = nums[nextIndex];
nums[nextIndex] = cacheItem;
cacheItem = temp;
p = nextIndex;
writeCount++;
} while (subLoopStartIndex !== p);
subLoopStartIndex++;
}
return;
};
export { rotate };