[leetcode]283. Move Zeroes移零

it2025-12-14  15

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.

Input: [0,1,0,3,12] Output: [1,3,12,0,0]

Note:

You must do this in-place without making a copy of the array.Minimize the total number of operations.

 

题意:

将数组中,一旦有 0 元素, 统统拖到数组末尾。

 

思路:

两个指针base,  i 从index为0的位置出发。

指针 i 用来扫数组,若 i 对应的元素非 0 时,

直接将指针 i 对应元素赋值给指针 base 对应元素,同时 base++。

这样,指针 i 遍历完毕数组,指针 base 也将所有非0元素保存在数组了 index [0 ~ i] 的位置

最后将数组 index ( i ~ nums.length ) 的后半部分都赋值为 0。

 

 

代码:

class Solution { public void moveZeroes(int[] nums) { int base = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] != 0){ nums[base] = nums[i]; base++; } } for(int i = base; i< nums.length; i++){ nums[i] = 0; } } }

 

转载于:https://www.cnblogs.com/liuliu5151/p/9059077.html

最新回复(0)