赞
踩
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
class Solution { public: void moveZeroes(vector<int>& nums) { int a=nums.size(); //两个指针分别从数组的开头 int left=0,right=0; //遍历数组遍历 while(right<a){ //如果不为0,发生两个指针数的交换 if(nums[right]){ swap(nums[right],nums[left]); //同时左指针右移 left++; } //如果为0,仅仅发生右指针右移动,然后下一次再次进行非0与0的交换 right++; } } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。