移动零
解法一:数组遍历
public class LeetCode_283 {
public static void moveZeroes(int[] nums) {
// 最后一个非0的位置
int theLastNotZeroPos = nums.length - 1;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] == 0) {
if (i != theLastNotZeroPos) {
for (int j = i; j < theLastNotZeroPos; j++) {
nums[j] = nums[j + 1];
}
nums[theLastNotZeroPos] = 0;
}
theLastNotZeroPos--;
}
}
}
public static void main(String[] args) {
int[] nums = new int[]{0, 1, 0, 3, 12};
System.out.println("-----移动前-----");
for (int num : nums) {
System.out.print(num + " ");
}
System.out.println();
moveZeroes(nums);
System.out.println("-----移动后-----");
for (int num : nums) {
System.out.print(num + " ");
}
}
}