问题:
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
我实现的程序:
var moveZeroes = function(nums) {
nums.forEach(function(val, key, arr){
if( (key+1) < arr.length) {
if(val === 0) {
arr[key] = arr[key+1];
arr[key+1] = 0;
}
}
});
};
运行结果:
Your input
[0,1,0,3,12]
Your answer
[1,0,3,12,0]
Expected answer
[1,3,12,0,0]
为什么没有得到期望的结果?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果arr[k+1]本来就是0呢,你这样做是不行的
forEach 是按照数组从左到右的顺序,将每个元素遍历
一次,当遍历到第一个元素0时,经过比较判断需要跟后面一个元素换位,此时数组就变成了[1, 0, 0, 3, 12]第二个元素此时已经变成了
0, 接着遍历到第二个元素,判断为0,继续换位(第2个0和第3个0互换)[1, 0, 0, 3, 12]同理
[1, 0, 3, 0, 12][1, 0, 3, 12, 0]所以 你的答案,只是把数组中出现的第一个
0移到末尾去c#的,通过leetcode,不过性能中等。
}