【题目描述】
给定一个数组 nums
,编写一个函数将所有 0
移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作
https://leetcode.cn/problems/move-zeroes/description/?favorite=2cktkvj&orderBy=most_votes
【示例】
【代码】admin
代码实现了基本要求,但LeeCode输出有问题
import java.util.*;
// 2022-12-17
class Solution {
public void moveZeroes(int[] nums) {
System.out.println("before: " + Arrays.toString(nums));
if (nums.length == 0) return;
int[] res = new int[nums.length];
int index = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] != 0){
res[index] = nums[i];
index++;
}
}
nums = res;
System.out.println("after: " + Arrays.toString(nums));
}
}
public class Main{
public static void main(String[] args) {
int[] arr = {0,1,0,3,12}; // 输出: 1,3,12,0,0
int[] arr1 = {0}; // 输出: 0
new Solution().moveZeroes(arr);
new Solution().moveZeroes(arr1);
}
}
public void moveZeroes(int[] nums) {
System.out.println("before: " + Arrays.toString(nums));
if (nums.length == 0) return;
// 确保不为0的数字在nums中下标自增
int index = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] != 0){
int tmp = nums[i];
nums[i] = nums[index];
nums[index] = tmp;
index++;
}
}
System.out.println("after: " + Arrays.toString(nums));
}
【代码】Jason365
解题思路
- 遍历数组,无为0的元素移动数组前方,用index下标记录。
- 遍历结束,对index值后的元素统一设为0
public void moveZeroes(int[] nums) {标签:index,nums,int,System,LeeCode,toString,println,283,移动 From: https://blog.51cto.com/u_13682316/5951019
System.out.println("before: " + Arrays.toString(nums));
int index = 0;
for (int num : nums) {
if (num != 0){
nums[index++] = num;
}
}
while (index < nums.length){
nums[index++] = 0;
}
System.out.println("after: " + Arrays.toString(nums));
}