javascript - leetcode遇到的一个题?
ringa_lee
ringa_lee 2017-04-10 16:06:53
[JavaScript讨论组]

问题:
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]

为什么没有得到期望的结果?

ringa_lee
ringa_lee

ringa_lee

全部回复(3)
ringa_lee

如果arr[k+1]本来就是0呢,你这样做是不行的

巴扎黑

forEach() executes the provided callback once for each element present in the array in ascending order.

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移到末尾去

PHP中文网

c#的,通过leetcode,不过性能中等。

public class Solution {
public void MoveZeroes(int[] nums) {
      var stack = new Stack<int>();
        int zeros = 0;

        for (var i = 0; i < nums.Length; i++)
        {
            if (nums[i] == 0)
            {
                zeros++;
                continue;
            }

            stack.Push(nums[i]);
        }

        for (var i = nums.Length - 1; i > nums.Length - 1 - zeros; i--)
        {
            nums[i] = 0;
        }

        for (var i = nums.Length -1 - zeros; i >= 0; i--)
        {
            nums[i] = stack.Pop();
        }
}

}

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号