File tree 2 files changed +58
-0
lines changed
solution/0100-0199/0189.Rotate Array
2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change @@ -136,6 +136,34 @@ var rotate = function (nums, k) {
136
136
};
137
137
```
138
138
139
+ 使用三次数组翻转 + 双指针实现翻转
140
+
141
+ ``` js
142
+ /**
143
+ * @param {number[]} nums
144
+ * @param {number} k
145
+ * @return {void} Do not return anything, modify nums in-place instead.
146
+ */
147
+ var rotate = function (nums , k ) {
148
+ k %= nums .length ;
149
+ // 使用三次数组翻转
150
+ reverse (nums, 0 , nums .length - 1 );
151
+ reverse (nums, 0 , k - 1 );
152
+ reverse (nums, k, nums .length - 1 );
153
+
154
+ };
155
+ function reverse (nums , start , end ) {
156
+ // 双指针实现翻转
157
+ while (start < end) {
158
+ const temp = nums[start];
159
+ nums[start] = nums[end];
160
+ nums[end] = temp;
161
+ start += 1 ;
162
+ end -= 1 ;
163
+ }
164
+ }
165
+ ```
166
+
139
167
### ** Go**
140
168
141
169
``` go
Original file line number Diff line number Diff line change @@ -99,6 +99,8 @@ class Solution {
99
99
100
100
### ** JavaScript**
101
101
102
+ the elements in the range ` k~n-1 ` of the array to the front with the native API.
103
+
102
104
``` js
103
105
/**
104
106
* @param {number[]} nums
@@ -111,6 +113,34 @@ var rotate = function (nums, k) {
111
113
};
112
114
```
113
115
116
+ Use three array reverses implemented by double pointers
117
+
118
+ ``` js
119
+ /**
120
+ * @param {number[]} nums
121
+ * @param {number} k
122
+ * @return {void} Do not return anything, modify nums in-place instead.
123
+ */
124
+ var rotate = function (nums , k ) {
125
+ k %= nums .length ;
126
+ // Use three array reverses
127
+ reverse (nums, 0 , nums .length - 1 );
128
+ reverse (nums, 0 , k - 1 );
129
+ reverse (nums, k, nums .length - 1 );
130
+
131
+ };
132
+ function reverse (nums , start , end ) {
133
+ // reverse implemented by double pointers
134
+ while (start < end) {
135
+ const temp = nums[start];
136
+ nums[start] = nums[end];
137
+ nums[end] = temp;
138
+ start += 1 ;
139
+ end -= 1 ;
140
+ }
141
+ }
142
+ ```
143
+
114
144
### ** Go**
115
145
116
146
``` go
You can’t perform that action at this time.
0 commit comments