本文介绍了给定一个数组nums,写一个函数将所有0移动到它的末尾,同时保持非零元素的相对顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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]





我尝试过:





What I have tried:

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        int count=0;
        for(int i=0;i<nums.size();i++)
        {
            if(nums[i]==0)
            {
                nums.erase(nums.begin()+i);
                ++count; //This is to count number of zeroes.
            }
        }
       for(int i=0;i<count;i++)
       
           nums.push_back(0);  //To input zero at the end of the vector count times.
       
}
};







此代码显示正确的输入输出:




This code shows the correct output for the input :

[0,1,0,3,12]



输入输出错误:


but wrong output for input:

[0,0,1]



输入时,

.
For input,

[0,0,1]

它显示

[0,1,0]

。它应该是

[1,0,0]

推荐答案

nums.erase(nums.begin()+i);



移动向量中的剩余值。

试试看看发生了什么


moves remaining values in vector.
try this to see what is going on

for(int i=0;i<nums.size();i++)
{
    if(nums[i]==0)
    {
        nums.erase(nums.begin()+i);
        ++count; //This is to count number of zeroes.
    }
    else
    {
        // add 100 to each nont zero tested
        nums[i]+=100
    }
}



-----

您的代码行为不符合您的预期,您不明白为什么!



有一个几乎通用的解决方案:逐步在调试器上运行代码,检查变量。

调试器在这里显示你的代码正在做什么和你的任务是与它应该做的比较。

调试器中没有魔法,它不知道你应该做什么,它没有找到bug,它只是帮助你通过向您展示正在发生的事情。当代码没有达到预期的效果时,你就接近了一个错误。

要查看你的代码在做什么:只需设置断点并查看代码是否正常运行,调试器允许你执行第1行第1行,并在执行时检查变量。

]

[]

调试器仅显示您的代码正在执行的操作,并且您的任务是与应该执行的操作进行比较。


-----
Your code do not behave the way you expect, and you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.
Debugger - Wikipedia, the free encyclopedia[^]
1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]
The debugger is here to only show you what your code is doing and your task is to compare with what it should do.


这篇关于给定一个数组nums,写一个函数将所有0移动到它的末尾,同时保持非零元素的相对顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:09