LeetCode 283:Move Zeroes

来源:互联网 发布:网络超市好开吗 编辑:程序博客网 时间:2024/05/17 08:45

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.

给定一个数组nums,编写一个能够将所有0放到数组最后并且保持其他元素为原来顺序的函数。

例如,给定nums=[0, 1, 0, 3, 12],调用函数之后数组应该变成num=[1, 3, 12, 0 0]

注意:

1.你必须在数组内完成所有操作,而不能复制另外一个数组。

2.尽可能的减少操作。


一开始想的是每找到一个0就放到最后面,然后把之前的所有数字都往前移一次,可是马上否决了这个方案,因为Note里面要求要使移动次数尽可能的小。。。于是想到了找第一个0与第一个第一个非0,需要注意的是结束位置

class Solution {public:    void moveZeroes(vector<int>& nums) {        int first_zero=0,first_nonzero=0;        for(int i=0;i<nums.size();i++)        {            for(;nums[first_zero]!=0;first_zero++)                if(first_zero==nums.size()-1) return;            for(first_nonzero=first_zero;nums[first_nonzero]==0;first_nonzero++)                if(first_nonzero==nums.size()-1) return;            int temp=nums[first_nonzero];            nums[first_zero]=temp;            nums[first_nonzero]=0;        }    }};



0 0
原创粉丝点击