283. Move Zeroes Add to List(把0移动到末尾)

来源:互联网 发布:淘宝卖家有ipad客户端 编辑:程序博客网 时间:2024/05/18 01:38

DescriptionSubmissionsSolutions
Total Accepted: 170660
Total Submissions: 349827
Difficulty: Easy
Contributor: LeetCode
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.

解法1:不合题意,题中不让用拷贝数组class Solution {public:    void moveZeroes(vector<int>& nums) {        vector<int> num1;//定义大小的话会用0填充        int sum=0;        for(int a:nums)        {            if(a==0)            {                sum++;//定义个计数器来几率0的个数            }            else {num1.push_back(a);}//不是0的话放前面        }        while(sum>0)        {            num1.push_back(0);//把0插到最后            sum--;        }        nums.clear();//清空原数组        nums=num1;    }};//解法2:class Solution {public:    void moveZeroes(vector<int>& nums) {        for (int i = 0, j = 0; i < nums.size(); ++i) //一个不停的向后扫(i),找到非零位置,然后和前面那个指针(j)交换位置即可        {            if (nums[i]) //如果不是0就交换            {                swap(nums[i], nums[j++]);            }        }    }};//解法3:道理同上class Solution {public:    void moveZeroes(vector<int>& nums) {        int left = 0, right = 0;        while (right < nums.size()) {            if (nums[right]) {                swap(nums[left++], nums[right]);            }            ++right;        }    }};
0 0
原创粉丝点击