描述: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.
翻譯:給定一個數組nums,寫一個函數將所有的值移動0到最後,同時保持非零元素的相對順序。
例如,nums = [0, 1, 0, 3, 12]在調用函數後,nums應該是[1, 3, 12, 0, 0]。
注意:
您必須在本地進行此操作,而無需製作數組的副本。
最小化操作總數。
代碼與思路:
/**
*移動非0元素到最後,其他元素放在最前面且保持相對位置
* @param nums
*/
public static void moveZeroes(int[] nums) {
int insertPostion = 0;
int len = nums.length;
for (int i = 0; i < len; i++) {
//這個if可以把數組中的非0元素向前
//現在insertPostion的大小就是非0元素的個數
if (nums[i]!=0)
nums[insertPostion++] = nums[i];
}
//現在可以計算出非0的個數:len-insertPostion
while (insertPostion<len) {
nums[insertPostion++] = 0;
}
}
public static void main(String[] args) {
int[] nums = {1,3,5,0,9,0,10};
moveZeroes(nums);
for (int i = 0; i < nums.length; i++) {
System.out.print(" "+nums[i]);
}
}
結果
1 3 5 9 10 0 0