給定一個數組 nums
,編寫一個函數將所有 0
移動到數組的末尾,同時保持非零元素的相對順序。
示例:
輸入:[0,1,0,3,12]
輸出:[1,3,12,0,0]
說明:
- 必須在原數組上操作,不能拷貝額外的數組。
- 儘量減少操作次數。
思路:
遍歷,另外在維護一個指向非0數的索引,噹噹前數字爲0,就將這個數字和索引指向的數字交換。
當索引已經在末尾了,則後面已經沒有非0數字了,就直接將數字置0就行了
/**
* Created with IntelliJ IDEA.
* Description:給定一個數組 nums,編寫一個函數將所有 0 移動到數組的末尾,同時保持非零元素的相對順序。
* 必須在原數組上操作,不能拷貝額外的數組。
儘量減少操作次數。
* User: hhj
* Date: 2018-08-26
* Time: 8:57
*/
public class MoveZeroes {
public static void moveZeroes(int[] nums) {
int index = 0;
int len = nums.length;
for (int i=0; i<len-1; i++){
if (index == len-1){
nums[i] = 0;
continue;
}
if (nums[i] == 0){
if (index<i){
index = i;
}
index++;
while (index<=len-2 && nums[index] == 0){
index++;
}
if (nums[index] != 0){
nums[i] = nums[index];
nums[index] = 0;
}
}
}
for (int num:nums){
System.out.println(num);
}
}
public static void main(String[] ars){
int[] arr = {0,1,0,3,12};
moveZeroes(arr);
}
}