LeetCode: 移动零


题目

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

1
2
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  • 必须在原数组上操作,不能拷贝额外的数组。
  • 尽量减少操作次数。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes

代码

Go

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main

import "fmt"

func moveZeroes(nums []int) []int {
prev_zero := -1

for i := 0; i < len(nums); i++ {
if nums[i] == 0 {
if prev_zero == -1 {
prev_zero = i
}
continue
}

if nums[i] != 0 && prev_zero >= 0 {
nums[prev_zero], nums[i] = nums[i], nums[prev_zero]
i, prev_zero = prev_zero, -1
}
}

return nums
}

func main() {
fmt.Println(moveZeroes([]int{0, 1, 0, 3, 12}))
fmt.Println(moveZeroes([]int{-959151711,
623836953,
209446690,
-1950418142,
1339915067,
-733626417,
481171539,
-2125997010,
-1225423476,
1462109565,
147434687,
-1800073781,
-1431212205,
-450443973,
50097298,
753533734,
-747189404,
-2070885638,
0,
-1484353894,
-340296594,
-2133744570,
619639811,
-1626162038,
669689561,
0,
112220218,
502447212,
-787793179,
0,
-726846372,
-1611013491,
204107194,
1605165582,
-566891128,
2082852116,
0,
532995238,
-1502590712,
0,
2136989777,
-2031153343,
371398938,
-1907397429,
342796391,
609166045,
-2007448660,
-1096076344,
-323570318,
0,
-2082980371,
2129956379,
-243553361,
-1549960929,
1502383415,
0,
-1394618779,
694799815,
78595689,
-1439173023,
-1416578800,
685225786,
-333502212,
-1181308536,
-380569313,
772035354,
0,
-915266376,
663709718,
1443496021,
-777017729,
-883300731,
-387828385,
1907473488,
-725483724,
-972961871,
-1255712537,
383120918,
1383877998,
1722751914,
0,
-1156050682,
1952527902,
-560244497,
1304305692,
1173974542,
-1313227247,
-201476579,
-298899493,
-1828496581,
-1724396350,
1933643204,
1531804925,
1728655262,
-955565449,
0,
-69843702,
-461760848,
268336768,
1446130876}))
}

评论