题目描述:
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]); } };
原文:https://www.cnblogs.com/harchar/p/10501976.html