<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">Given an array </span><code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12.6px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">nums</code><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">, write a function to move all </span><code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12.6px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">0</code><span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">'s to the end of it while maintaining the relative order of the non-zero elements.</span>
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [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.
这道题用两个“指针”,开始是i = 0 ; j = 0;
可以把i理解为不等于零的个数,并且是放着不为零的最后一个数下标的后以为;从第一个开始,j为当前知道的的地方;
当nums[j] != 0;如果i!=j;把j下表放的数转移到 i 下表中,并置nums[j]=0;移动 i ;
void moveZeroes(int* nums, int numsSize) {
int i=0,j=0;
for(;j<numsSize;j++)
{
if(nums[j] != 0)
{
if(i!=j)
{
nums[i] = nums[j];
nums[j] = 0;
}
i++;
}
}
}