LeetCode 283. Move Zeroes

来源:互联网 发布:淘宝考试下列旅游景点 编辑:程序博客网 时间:2024/06/04 00:23

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.


题目大意:

将给定数组中的所有的0元素都移动数组的最后,其他元素都移动到前面。
如果直接模拟,判断当前元素是0的话,然后把0放到最后一位,后面的元素往前移,这样操作会很麻烦。
我们不妨把思路反转一下,直接把非0的元素往前移动,移动到他应该到的地方,那么我们怎么能知道他应该在哪里呢,我们定义一个变量j用来记录当前元素放到了哪个位置,j从0开始,然后遍历数组,如果当前元素不是0,那么把这个元素放到j位置,并且j后移,如果是0,j保持不变,即下一个非0元素要放到这里,那么当我们遍历到下一个非0元素的时候,就可以把他放在j位置,循环操作此步骤就可以把所有的非0元素都归位。
非0元素归位以后,我们要做的就是在非0元素的最后加上0即可。


题目代码:

class Solution {public:    void moveZeroes(vector<int>& nums) {        int i = 0, j = 0;        for(i = 0; i < nums.size(); i++){            if(nums[i])                nums[j++] = nums[i];        }        for(; j < nums.size(); j++){            nums[j] = 0;        }    }};


原创粉丝点击