leetCode283.MoveZeroes数组-创新互联

283. Move Zeroes

我们注重客户提出的每个要求,我们充分考虑每一个细节,我们积极的做好网站设计制作、网站建设服务,我们努力开拓更好的视野,通过不懈的努力,创新互联建站赢得了业内的良好声誉,这一切,也不断的激励着我们更好的服务客户。 主要业务:网站建设,网站制作,网站设计,小程序开发,网站开发,技术开发实力,DIV+CSS,PHP及ASP,ASP.Net,SQL数据库的技术开发工程师。

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元素,保持原来的顺序。

代码如下:

class Solution {
public:
    void moveZeroes(vector& nums) {
        int step = 0;
        for(int i = 0 ; i < nums.size();i++)
        {
            if(nums[i] == 0)
            {
                step++;
            }
            else
            {
                nums[i - step] = nums[i];
                if(step != 0)
                    nums[i] = 0;
            }
        }
    }
};

2016-08-12 01:26:32

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


文章标题:leetCode283.MoveZeroes数组-创新互联
URL链接:http://pwwzsj.com/article/dpsdds.html