File tree Expand file tree Collapse file tree 1 file changed +30
-9
lines changed Expand file tree Collapse file tree 1 file changed +30
-9
lines changed Original file line number Diff line number Diff line change @@ -31,9 +31,11 @@ Minimize the total number of operations.
3131无
3232
3333## 代码
34- * 语言支持:JS,C++
34+
35+ * 语言支持:JS, C++, Python
3536
3637JavaScript 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+
8588C++ Code:
89+
8690> 解题思想与上面JavaScript一致,做了少许代码优化(非性能优化,因为时间复杂度都是O(n)):
8791> 增加一个游标来记录下一个待处理的元素的位置,这样只需要写一次循环即可。
92+
8893``` C++
8994class Solution {
9095public:
@@ -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+ ```
You can’t perform that action at this time.
0 commit comments