给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
题解:
这里比如原数组是 [0,1,0,3,12]
新数组为空
第一次循环: [0]
第一次循环: [1,0]
第一次循环: [1,0,0]
第一次循环: [1,3,0,0]
第一次循环: [1,3,12,0,0]
java实现
class Solution {
public static void moveZeroes(int[] nums) {
int[] arr = new int[nums.length];
int j = 0;
int length = nums.length - 1;
for (int num : nums) {
if (num != 0) {
arr[j] = num;
j++;
} else {
arr[length--] = 0;
}
}
for (int i : arr) {
System.out.println(i);
}
}
}
public static void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[j++] = nums[i];
}
}
while (j < nums.length) {
nums[j++] = 0;
}
for (int i : nums) {
System.out.println(i);
}
}
比如第一次循环 i = 0, j 为 0,因为第一个非0元素要存储的位置就是 0
第二次循环 i != 0 则nums[i] 与nums[j] 相互交换,让第一个位置为1,第二个位置为0,j++,即下一个非0元素存储的位置为1,然后如果有下个非0元素继续与j交换位置
public static void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
if (i != j) {
nums[j] = nums[i];
nums[i] = 0;
}
j++;
}
}
for (int i: nums) {
System.out.println(i);
}
}
本文地址:https://blog.csdn.net/qq_42651904/article/details/107621043
如对本文有疑问, 点击进行留言回复!!
pycharm 2020 Error: failed to send plot to http://127.0.0.1:63342
网友评论