1. 題目描述
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.
給定一個數組,將數組中所有的0移動到數組尾部。
2. 解題思路
題目與[27] Remove Element和 [26] Remove Duplicates from Sorted Array相似,都涉及到了對數組中一些元素進行移動的問題,答題的思路就是,將滿足的放到前面,不滿足的直接覆蓋或者交換到後面。本題就是採用了交換的方式,首先找到第一個0記錄位置i,再找到第一個非0記錄位置j,將i與j交換,交換後i向後移動一個位置,j繼續向後查找非0元素,重複交換的過程直至j走到數組的最後。
3. Code
public class Solution {
public void moveZeroes(int[] nums) {
for(int i = 0, j = 1; j < nums.length; ++j)
{
// 找到第一個0
if(nums[i] == 0)
{
// 找到第一個非0
if(nums[j] != 0)
{
// 交換
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
++i;
}
}
else
{
// 如果當前不是0,ij後移
++i;
}
}
}
}