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:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.
题目大意,给出一个数字数组,要求将数组中为0的元素移到数组的尾端。并且保留非0元素的相对位置不变。要求不要复制数组并且最小化操作数。
(1)假设数组中有j个非零元素,将j个非零元素移动到数组的前j个位置;然后将n-j个元素(即为0的元素)置为0。
解法一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class Solution { public: void moveZeroes(vector<int>& nums) { int i,j=0; for ( i = 0; i < nums.size(); ++i) { if (nums[i] != 0) { nums[j] = nums[i]; ++j; } } //nums[j]及后面的元素赋值为0 for ( j; j < nums.size(); ++j) nums[j] = 0; } }; |