leetcode---Move Zeroes

来源:互联网 发布:js为什么禁止跨域请求 编辑:程序博客网 时间:2024/05/27 20:21

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.

class Solution {public:    void moveZeroes(vector<int>& nums) {        int len = nums.size();        if(len == 0 || len == 1)        {            return;        }        int i;        int index;        int len1 = 0;        int n = 0;    //最后一个数字前面0的个数        int n1 = 0;   //最后一个数字后面0的个数        int j = len-1;        while(j && nums[j]==0)        {            n1++;            j--;        }        if(n1 == len) //全都是0            return;        for(i=len-n1-1; i>=0; i--)  //从后往前        {            if(nums[i] == 0)            {                index = i;                len1 = 1;   //连续0的个数                int j = i;                while(j>0 && nums[--j] == 0)                  {                    len1++;                }                n += len1;   //到目前为止所找到的最后一个数字前面0的个数                for(j=index-len1+1; j<len-n; j++)  //直接将数字移动连续0个数的位置                    nums[j] = nums[j+len1];            }        }        for(i=len-n-n1; i<len; i++)            nums[i] = 0;    }};
0 0
原创粉丝点击