LeetCode--Move Zeroes
题目:
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.
void moveZeroes(vector<int>& nums) { int i = 0; int j = 0; int temp = 0; if(nums.size() < 1) { return; } else { while(nums[i] != 0 && i < nums.size()) //先找到第一个为0的位置 { ++i; } if(i == nums.size())//如果已经是最后一个,不用继续了,返回 { return; } else { j = i+1; while(j < nums.size() && nums[j] == 0)//找到下一个不为0的数 { ++j; } if(j == nums.size()) //超过最大索引值,说明0后面没有非0数了 { return; } else //交换这两个数 { temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; moveZeroes(nums); } } } }