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. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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 zero,temp;
zero = -1;
for(int i = 0;i<nums.size();i++){
if(nums[i] ==0 && zero == -1)
zero = i;
if(nums[i] != 0 && zero != -1){
nums[zero] = nums[i];
nums[i] = 0;
zero++;
}
}
}
};
这个是16ms的,下面贴出一个20ms的:
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int nonZeroPartion = 0;
int temp;
for(int i = 0;i < nums.size();i++){
if(nums[i] != 0){
temp = nums[i];
nums[i] = nums[nonZeroPartion];
nums[nonZeroPartion++] = temp;
}
}
}
};
此题不准改变顺序,而且也不准利用额外的数组,所以利用2-points来解此题。对于第一段代码,利用一个zero来记录第一个“0“的位置,往后遍历,遇到非0的数就与之置换,zero++比较精髓。