力扣283题---零移动
给定一个数组nums,编写一个函数将所有0移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:输入: nums = [0,1,0,3,12] 输出: [1,3,12,0,0]
示例 2:输入: nums = [0] 输出: [0]
方法代码如下:
class Solution {
public void moveZeroes(int[] nums) {
int len = nums.length;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[i] == 0 && nums[j] != 0) {
int temp =nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
}
}
}
测试:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {0, 1, 0, 3, 12};//[1,3,12,0,0]
Main solution = new Main();
solution.moveZeroes(nums);
}
public void moveZeroes(int[] nums) {
int len = nums.length;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (nums[i] == 0 && nums[j] != 0) {
int temp =nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
}
System.out.println(Arrays.toString(nums));
}
}
输出:[1, 3, 12, 0, 0]
精练写法:
把非0的往前挪,挪完之后,后面的就用0覆盖。
方法代码:
public void moveZeroes(int[] nums) {
int index = 0;
//一次遍历,把非零的都往前挪
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0)
nums[index++] = nums[i];
}
//后面的都是0,
while (index < nums.length) {
nums[index++] = 0;
}
}
测试用例:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {0, 1, 0, 3, 12, 1, 3, 0, 0, 0, 0, 1, 6};//[1,3,12,0,0]
Main solution = new Main();
solution.moveZeroes(nums);
}
public void moveZeroes(int[] nums) {
int index = 0;
//一次遍历,把非零的都往前挪
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0)
nums[index++] = nums[i];
}
//后面的都是0,
while (index < nums.length) {
nums[index++] = 0;
}
System.out.println(Arrays.toString(nums));
}
}
输出:[1, 3, 12, 1, 3, 1, 6, 0, 0, 0, 0, 0, 0]