将零移动到JavaScript中的数组末尾-如何不返回任何内容? [英] Move zeroes to end of array in javascript - how to return nothing?

查看:87
本文介绍了将零移动到JavaScript中的数组末尾-如何不返回任何内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用JS完成一个 leetcode.com问题。一般而言,我是算法新手,在接受我的第一次提交时遇到了一些麻烦。

I am attempting to complete a leetcode.com question in JS. I am new to algorithms in general, and am having some trouble getting my first submission accepted.

问题指定了以下内容:

给出一个数组 nums ,编写一个函数,将所有0移到它的末尾,同时保持非零元素的相对顺序。

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.

例如,给定 nums = [0,1,0,3,12] ,在调用函数后,数字应该为 [1、3、12、0、0]

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

注:
您必须就地执行此操作,而不需要复制数组。
最小化操作总数。

Note: You must do this in-place without making a copy of the array. Minimize the total number of operations.

这就是我的代码:

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    var i, temp;

    for (i = 0; i < nums.length-1; i++) {
        if(nums[i] === 0) {
            temp = nums.splice(i, 1);
            nums.push(temp[0]);
        }
    }
    return null;
};

代码示例顶部的注释在其文本编辑器中提供,使我相信我不应该提供任何退货声明。尽管他们网站上的验证程序似乎根本不想接受,但我开始返回null ...

The comments at the top of the code sample are provided in their text editor, and led me to believe that I am not supposed to provide any return statement. Though the validator on their site seemed to not want to accept that at all, so I started returning null...

当我记录我的 nums时处理到控制台后,我看到期望的结果 nums = [1、3、12、0、0] 。不管我的回答如何,我都会被拒绝。我很想了解我在这里做错了什么,所以我可以解决它。

When I log my nums to the console after handling the input, I am seeing the desired result nums = [1, 3, 12, 0, 0]. Regardless my answer keeps getting rejected. I would love to understand what I am doing wrong here, so I can fix it.

我知道这可能是重复的。我看到了其他有关C和Java的响应,但是没有看到与JS相关的响应。

I understand this may be a duplicate. I saw other responses dealing with C and Java, but none I saw dealt with JS.

推荐答案

该问题与返回语句,问题是您的算法错误。

The problem has nothing to do with the return statement, the issue is your algorithm is wrong.

[0,0,1,2,3] 将返回 [0,1,2,3,0]

当您沿正方向循环时,删除索引,则在下一个索引滑到您已经覆盖的位置时跳过索引。

When you loop in the positive direction and remove indexes, you skip indexes as the next index slides down to the position you already covered.

您需要向负方向循环。

You need to loop in the negative direction. Start at the end and go to the start.

for (i = nums.length-1; i>=0; i--) {

这篇关于将零移动到JavaScript中的数组末尾-如何不返回任何内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆