File tree 2 files changed +41
-1
lines changed
2 files changed +41
-1
lines changed Original file line number Diff line number Diff line change 6
6
| 2| [ 两数相加] ( https://leetcode-cn.com/problems/add-two-numbers/ ) | [ JavaScript] ( ./algorithms/add-two-numbers.js ) | Medium|
7
7
| 7| [ 整数反转] ( https://leetcode-cn.com/problems/reverse-integer/ ) | [ JavaScript] ( ./algorithms/reverse-integer.js ) | Medium|
8
8
| 9| [ 回文数] ( https://leetcode-cn.com/problems/palindrome-number/ ) | [ JavaScript] ( ./algorithms/palindrome-number.js ) | Easy|
9
- | 14| [ 最长公共前缀] ( https://leetcode-cn.com/problems/longest-common-prefix/ ) | [ JavaScript] ( ./algorithms/longest-common-prefix.js ) | Easy|
9
+ | 14| [ 最长公共前缀] ( https://leetcode-cn.com/problems/longest-common-prefix/ ) | [ JavaScript] ( ./algorithms/longest-common-prefix.js ) | Easy|
10
+ | 189| [ 轮转数组] ( https://leetcode-cn.com/problems/rotate-array/ ) | [ JavaScript] ( ./algorithms/rotate-array.js ) | Medium|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[] } nums
3
+ * @param {number } k
4
+ * @return {void } Do not return anything, modify nums in-place instead.
5
+ */
6
+
7
+ // 空间复杂度O(1)
8
+ var rotate = function ( nums , k ) {
9
+ k %= nums . length ;
10
+
11
+ const reverse = ( nums , start , end ) => {
12
+ while ( start < end ) {
13
+ [ nums [ start ++ ] , nums [ end -- ] ] = [ nums [ end ] , nums [ start ] ] ;
14
+ }
15
+ } ;
16
+
17
+ // 反转整个数组
18
+ reverse ( nums , 0 , nums . length - 1 ) ;
19
+ // 反转前k个元素
20
+ reverse ( nums , 0 , k - 1 ) ;
21
+ // 反转后k后面的元素
22
+ reverse ( nums , k , nums . length - 1 ) ;
23
+ } ;
24
+
25
+ // 空间复杂度O(n)
26
+ var rotate = function ( nums , k ) {
27
+ const len = nums . length ;
28
+ const copy = [ ] ;
29
+
30
+ for ( let i = 0 ; i < len ; i ++ ) {
31
+ copy . push ( nums [ i ] ) ;
32
+ }
33
+
34
+ for ( let i = 0 ; i < len ; i ++ ) {
35
+ const nextIndex = ( i + k ) % len ;
36
+
37
+ nums [ nextIndex ] = copy [ i ] ;
38
+ }
39
+ } ;
You can’t perform that action at this time.
0 commit comments