leetcode283 - Move Zeroes - easy
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.
Example:
Input:[0,1,0,3,12]Output:[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.
同向双指针。i loop 整个input,j用来表示output的index,i找到非0数的时候,就写进j。
i遍历结束后,从j的位置往后就全是0了
实现:
1 class Solution { 2 public: 3 void moveZeroes(vector<int>& nums) { 4 5 int i = 0, j = 0; 6 while (i < nums.size()){ 7 if (nums[i] != 0){ 8 nums[j++] = nums[i]; 9 } 10 i++; 11 } 12 13 while (j < nums.size()){ 14 nums[j++] = 0; 15 } 16 17 } 18 };

浙公网安备 33010602011771号