Come from : [https://leetcode-cn.com/problems/move-zeroes/]
283. Move Zeroes
1.Question
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 :
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
2.Answer
easy 类型题目。
这题我走了好多弯路。。。
感觉自己好蠢啊。。。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int count = nums.size();
int i = 0;
while(count)
{
if(0 == nums[i])
{
for(int j = i; j < nums.size() - 1; ++j)
{
nums[j] = nums[j+1];
}
nums[nums.size() - 1] = 0;
--count;
}
else
{
++i;
--count;
}
}
}
};
3.大神们的解决方案
方法1(有点两个辅助值的意思):思路:
- 定义一个变量 j ,表示非0数的个数,循环遍历数组,
- 如果不是0,将非0值移动到第 j 位置, 然后j++
- 遍历结束之后,如果 j < nums.size() ,其余全部补0。
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int i = 0,j = 0;
int numsSize = nums.size();
for(i = 0 ; i < numsSize; i++)
{
if(nums[i] != 0)
{
nums[j++] = nums[i];
}
}
while(j < numsSize)
{
nums[j++] = 0;
}
}
};
方法2:
class Solution {
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int k = 0;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i] != 0)
{
if(k != i)
{
swap(nums[i],nums[k]);
}
k++;
}
}
}
};
4.我的收获
细心啊 啊 啊!!!
2019/5/9 胡云层 于南京 74