題目描述
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:
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.
代碼
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int i = 0;
for (int j=0; j<n; ++j) {
if (nums[j]) {
swap(nums[i], nums[j]);
i++;
}
}
return;
}
};
爲什麼別人家的代碼總是能這麼簡潔。。。