Skip to content

Commit a5a17ea

Browse files
authored
Create 0283 Move Zeroes.md
1 parent 9cdd202 commit a5a17ea

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

two pointer/0283 Move Zeroes.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# 283. Move Zeroes
2+
https://leetcode-cn.com/problems/move-zeroes/
3+
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
4+
Note that you must do this in-place without making a copy of the array.
5+
6+
Example 1:
7+
Input: nums = [0,1,0,3,12]
8+
Output: [1,3,12,0,0]
9+
10+
Example 2:
11+
Input: nums = [0]
12+
Output: [0]
13+
14+
Constraints:
15+
1 <= nums.length <= 10^4
16+
-2^31 <= nums[i] <= 2^31 - 1
17+
18+
19+
Follow up: Could you minimize the total number of operations done?
20+
21+
``` python3
22+
class Solution:
23+
def moveZeroes(self, nums: List[int]) -> None:
24+
"""
25+
Do not return anything, modify nums in-place instead.
26+
"""
27+
slow,fast,n=0,1,len(nums)
28+
while fast<n:
29+
if nums[slow]==0 and nums[fast]!=0:
30+
nums[slow],nums[fast]=nums[fast],nums[slow]
31+
if nums[slow]!=0:
32+
slow+=1
33+
if nums[fast]==0 or fast<=slow:
34+
fast+=1
35+
```

0 commit comments

Comments
 (0)