LeetCode--Move Zeroes

题目:

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.
代码:

    void moveZeroes(vector<int>& nums) {
        int i = 0;
        int j = 0;
        int temp = 0;
        if(nums.size() < 1)
        {
            return;
        }
        else
        {
          while(nums[i] != 0 && i < nums.size()) //先找到第一个为0的位置
          {
             ++i;
          }
          if(i  == nums.size())//如果已经是最后一个,不用继续了,返回
          {
              return;
          }
          else
          {
            j = i+1;
            while(j < nums.size() && nums[j] == 0)//找到下一个不为0的数
            {
                ++j;
            }      
      
            if(j == nums.size()) //超过最大索引值,说明0后面没有非0数了
            {
                 return;
            }
            else //交换这两个数
            {
                temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                moveZeroes(nums);
            }    
          }
        }
    }


posted on 2015-11-03 11:10  小二杰  阅读(88)  评论(0编辑  收藏  举报

导航