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.
移动零。
题意很直观,将数组中所有0移动到数组的末端。要求必须in-place做。
思路是给一个cur指针和一个i指针,用i去遍历数组。当数组遇到非0的数字的时候,就放到cur的位置,cur++。如果扫描完整个数组cur的位置没有到达数组末尾,后面的位置用0补齐。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public void moveZeroes(int[] nums) { 3 int cur = 0; 4 for (int i = 0; i < nums.length; i++) { 5 if (nums[i] != 0) { 6 nums[cur] = nums[i]; 7 cur++; 8 } 9 } 10 while (cur < nums.length) { 11 nums[cur] = 0; 12 cur++; 13 } 14 } 15 }
JavaScript实现
1 /** 2 * @param {number[]} nums 3 * @return {void} Do not return anything, modify nums in-place instead. 4 */ 5 var moveZeroes = function(nums) { 6 let cur = 0; 7 for (let i = 0; i < nums.length; i++) { 8 if (nums[i] !== 0) { 9 nums[cur] = nums[i]; 10 cur++; 11 } 12 } 13 while (cur < nums.length) { 14 nums[cur] = 0; 15 cur++; 16 } 17 };