# LeetCode 283：移动零 Move Zeroes

2019.07.13 11:51 339浏览

Given an array `nums`, write a function to move all `0`'s to the end of it while maintaining the relative order of the non-zero elements.

**示例:**

```

```

**说明**:

1. 必须在原数组上操作，不能拷贝额外的数组。

2. 尽量减少操作次数。

**Note**:

1. You must do this **in-place** without making a copy of the array.

2. Minimize the total number of operations.

### 解题思路：

### Java：

```java

class Solution {

public void moveZeroes(int[] nums) {

int numsLen = nums.length;

if (numsLen < 1) return;//数组长度小于一直接返回

int j = 0;

for (int i = 0; i < numsLen; i++) {//遍历数组

if (nums[i] != 0) {//如果该数不为0

nums[j++] = nums[i];//赋值给索引j

}

}

while (j < numsLen) nums[j++] = 0;//把从j到末尾所有数字赋值0

}

}

```

### Python3：

```python

class Solution:

def moveZeroes(self, nums: List[int]) -> None:

"""

Do not return anything, modify nums in-place instead.

"""

if len(nums) < 1:

return

j = 0

for num in nums:

if num != 0:

nums[j] = num

j += 1

for i in range(j, len(nums)):

nums[i] = 0

```

`nums = [i *for* i in nums *if* i != 0]+[i *for* i in nums *if* i == 0]`

> 爱写bug（ID：iCodeBugs）

0人点赞

• 推荐
• 评论
• 收藏
• 共同学习，写下你的评论

0/150