Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2eef0e1

Browse files
ybian19azl397985856
authored andcommitted
feat: 283.move-zeroes add Python3 implementation (azl397985856#142)
1 parent 6599c5e commit 2eef0e1

File tree

1 file changed

+30
-9
lines changed

1 file changed

+30
-9
lines changed

‎problems/283.move-zeroes.md‎

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,11 @@ Minimize the total number of operations.
3131
3232

3333
## 代码
34-
* 语言支持:JS,C++
34+
35+
* 语言支持:JS, C++, Python
3536

3637
JavaScript Code:
38+
3739
```js
3840
/*
3941
* @lc app=leetcode id=283 lang=javascript
@@ -50,19 +52,19 @@ JavaScript Code:
5052
*
5153
* Given an array nums, write a function to move all 0's to the end of it while
5254
* maintaining the relative order of the non-zero elements.
53-
*
55+
*
5456
* Example:
55-
*
56-
*
57+
*
58+
*
5759
* Input: [0,1,0,3,12]
5860
* Output: [1,3,12,0,0]
59-
*
61+
*
6062
* Note:
61-
*
62-
*
63+
*
64+
*
6365
* You must do this in-place without making a copy of the array.
6466
* Minimize the total number of operations.
65-
*
67+
*
6668
*/
6769
/**
6870
* @param {number[]} nums
@@ -82,9 +84,12 @@ var moveZeroes = function(nums) {
8284
}
8385
};
8486
```
87+
8588
C++ Code:
89+
8690
> 解题思想与上面JavaScript一致,做了少许代码优化(非性能优化,因为时间复杂度都是O(n)):
8791
> 增加一个游标来记录下一个待处理的元素的位置,这样只需要写一次循环即可。
92+
8893
```C++
8994
class Solution {
9095
public:
@@ -101,7 +106,23 @@ public:
101106
++nonZero;
102107
}
103108
++next;
104-
}
109+
}
105110
}
106111
};
107112
```
113+
114+
Python Code:
115+
116+
```python
117+
class Solution:
118+
def moveZeroes(self, nums: List[int]) -> None:
119+
"""
120+
Do not return anything, modify nums in-place instead.
121+
"""
122+
slow = fast = 0
123+
while fast < len(nums):
124+
if nums[fast] != 0:
125+
nums[fast], nums[slow] = nums[slow], nums[fast]
126+
slow += 1
127+
fast += 1
128+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /