File tree 2 files changed +47
-1
lines changed
2 files changed +47
-1
lines changed Original file line number Diff line number Diff line change 193
193
| 287| [ Find the Duplicate Number] ( https://leetcode.com/problems/find-the-duplicate-number/ ) | | Hard|
194
194
| 285| [ Inorder Successor in BST] ( https://leetcode.com/problems/inorder-successor-in-bst/ ) &hearts ; | | Medium|
195
195
| 284| [ Peeking Iterator] ( https://leetcode.com/problems/peeking-iterator/ ) | | Medium|
196
- | 283| [ Move Zeroes] ( https://leetcode.com/problems/move-zeroes/ ) | | Easy|
196
+ | 283| [ Move Zeroes] ( https://leetcode.com/problems/move-zeroes/ ) | [ js ] ( ./algorithms/moveZeroes/solution.js ) | Easy|
197
197
| 282| [ Expression Add Operators] ( https://leetcode.com/problems/expression-add-operators/ ) | | Hard|
198
198
| 279| [ Perfect Squares] ( https://leetcode.com/problems/perfect-squares/ ) | | Medium|
199
199
| 278| [ First Bad Version] ( https://leetcode.com/problems/first-bad-version/ ) | | Easy|
Original file line number Diff line number Diff line change
1
+ // 解法一:双循环,这是很笨的一种实现方式,时间复杂度也很高
2
+ var moveZeroes = function ( nums ) {
3
+ let x = 0 ;
4
+ while ( x < nums . length ) {
5
+ if ( nums [ x ] === 0 ) {
6
+ let y = x + 1 ;
7
+ while ( x < nums . length - 1 && y < nums . length - 1 && nums [ y ] === 0 ) {
8
+ y ++ ;
9
+ }
10
+ if ( nums [ y ] ) {
11
+ [ nums [ x ] , nums [ y ] ] = [ nums [ y ] , nums [ x ] ]
12
+ }
13
+ }
14
+ x ++ ;
15
+ }
16
+ return nums ;
17
+ } ;
18
+
19
+ // 解法二:双循环的第二种解法
20
+ var moveZeroes = function ( nums ) {
21
+ let y = 0 ;
22
+ // 第一次遍历的时候,y指针记录非0的个数,只要是非0的统统都赋给nums[y]
23
+ for ( let x = 0 ; x < nums . length ; x ++ ) {
24
+ if ( nums [ x ] !== 0 ) {
25
+ nums [ y ++ ] = nums [ x ] ;
26
+ }
27
+ }
28
+ // 非0元素统计完了,剩下的都是0了
29
+ // 所以第二次遍历把末尾的元素都赋为0即可
30
+ for ( let x = y ; x < nums . length ; x ++ ) {
31
+ nums [ x ] = 0 ;
32
+ }
33
+ return nums ;
34
+ } ;
35
+
36
+ // 解法三:快排的思想(利用0,不等于0的都放到0的左边),达到一次循环
37
+ var moveZeroes = function ( nums ) {
38
+ let y = 0 ;
39
+ for ( let x = 0 ; x < nums . length ; x ++ ) {
40
+ //当前元素!=0,就把其交换到左边,等于0的交换到右边
41
+ if ( nums [ x ] !== 0 ) {
42
+ [ nums [ x ] , nums [ y ++ ] ] = [ nums [ y ] , nums [ x ] ] ;
43
+ }
44
+ }
45
+ return nums ;
46
+ } ;
You can’t perform that action at this time.
0 commit comments