题目:
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 { 2 public: 3 void moveZeroes(vector & nums) { 4 vector ::size_type i; 5 for(i=0;i < nums.size();i++) 6 { 7 vector ::iterator it = find(nums.begin(),nums.end()-i,0); 8 if(it == nums.end()-i) 9 break;10 else11 {12 nums.erase(it);13 nums.push_back(0);14 }15 }16 }17 };
最然通过了,但是时间长,感觉想法也比较笨,事实上通过一次遍历即可
1 class Solution { 2 public: 3 void moveZeroes(vector & nums) { 4 int n = nums.size(); 5 int left = 0, right = 0; 6 while (right < n){ 7 if (nums[right]){ 8 nums[left] = nums[right]; 9 left++;10 }11 right++;12 }13 while (left < n)14 nums[left++] = 0;15 }16 };