Problem:
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.
思路:
Solution (C++):
void moveZeroes(vector<int>& nums) {
int n = nums.size(), count = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] == 0) count++;
else nums[i-count] = nums[i];
}
for (int i = 0; i < count; ++i) {
nums[n-1-i] = 0;
}
}
性能:
Runtime: 12 ms Memory Usage: 7.4 MB
思路:
Solution (C++):
性能:
Runtime: ms Memory Usage: MB