LeetCode_283

题目描述:

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.

实现思路:

定义区间 [0,k) 为非零元素,遍历nums,当元素不为0时将其与nums[k]互换,[k,n)内剩余的元素自然就是0

代码如下:

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

 

posted on 2019-03-09 17:03  harchar  阅读(88)  评论(0)    收藏  举报

导航