283. Move Zeroes

来源:互联网 发布:淘宝联盟机器人发单 编辑:程序博客网 时间:2024/05/29 02:36

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的元素全都移至数组的前部分,后将后部分元素至为0void moveZeroes(vector<int>& nums) {        int j = 0;        for(int i = 0; i < nums.size(); i++){            if(nums[i]!=0)                nums[j++] = nums[i];        }        for(; j < nums.size(); j ++){            nums[j] = 0;        }    }

方法二、

void moveZeroes(vector<int>& nums) {        int last = 0; //last用来保存数组中第一个为0的元素的下标        int cur = 0;//cur用来保存当前遍历到的元素的下标        while(cur < nums.size()){            if(nums[cur] != 0){                swap(nums[last],nums[cur]);                last++;            }            cur++;        }
0 0
原创粉丝点击