Move Zeros

来源:互联网 发布:金十数据手机安卓版 编辑:程序博客网 时间:2024/04/27 15:24

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.

解法:使用双指针,将非零的数字全都往前存储,将后面的位置置为0即可。

void moveZeroes(vector<int>& nums) {    int pos = 0;    for (int i = 0; i < nums.size(); i++){        if (nums[i] != 0){            nums[pos++] = nums[i];        }    }    for (; pos < nums.size(); pos++){        nums[pos] = 0;    }}

参考:http://segmentfault.com/a/1190000003768716

0 0
原创粉丝点击