移動零
給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。
示例:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說明:
- 必須在原數組上操作,不能拷貝額外的數組。
- 儘量減少操作次數。
分析
維護index,記錄非0數字應當存放的位置。
代碼
void moveZeroes(int* nums, int numsSize)
{
int index = 0;
for(int i =0; i< numsSize; i++)
{
if(nums[i]!=0)
{
nums[index]= nums[i];
index ++;
}
}
while(index<numsSize)
{
nums[index++] = 0;
}
return ;
}
轉自: