Move Zeroes
描述:
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.
Example:
given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.
思路:在保持原有數(shù)組順序的情況下把0去掉。不能新建數(shù)組,最小化操作步數(shù)。遍歷數(shù)組,遇到0做一個標記,然后繼續(xù)向下遍歷遇到第一個非0的再做一個標記,將這兩個位置互換。重復(fù)該操作。
問題:
要注意第二層for循環(huán)中的判斷條件應(yīng)該有兩個,j<numsSize&&nums[j]==0,如果只有后一個會出現(xiàn)數(shù)組讀取越界的情況并與數(shù)組外的非零值進行交換,因而要加上數(shù)組的長度邊界判斷。
同時,如果不做優(yōu)化的話這樣的運行速度會很低,因此進行了兩步優(yōu)化。一是在第二層for循環(huán)中判斷并賦予j開始的值,使其減少重復(fù)比較;二是加入flag標志目的在于在第二層for循環(huán)的某一次中若已經(jīng)遍歷完成數(shù)組,則直接跳出循環(huán),避免了第一層for循環(huán)執(zhí)行的重復(fù)。確實提高了運行速度,但是相對而言還是較慢。
代碼:
void moveZeroes(int* nums, int numsSize) {
int i;
int j=0;
int temp;
int p;
int q=0;
for(i=0;i<numsSize;i++){
if(nums[i]==0){
p=i;
if(p>j){
q=p;
}
else{
q=j;
}
for(j=q+1;(j<numsSize&&nums[j]==0);){
j++;
}
int flag=1;
if(j<numsSize){
temp=nums[j];
nums[j]=nums[i];
nums[i]=temp;
flag=0;
}
if(flag)
return;
}
}
}