題目: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.
Notice
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
思路:
兩個指針
left 指向目前最後一個非0的數(shù)
right 往後找非 0 冰评,找到後和 left++ 交換
代碼:
public:
/**
* @param nums: an integer array
* @return: nothing
*/
void moveZeroes(vector<int> &nums) {
// write your code here
int left = 0;
int right = 0;
//left 指向目前最後一個非0的數(shù)
//right 往後找非 0 此虑,找到後和 left++ 交換
while( right < nums.size()){
if(nums[right]){
swap(nums[left++], nums[right]);
}
right++;
}
}
};