【问题标题】:Another interview question in Javascript: removing items from the middle of an array using just .push .popJavascript 中的另一个面试问题:仅使用 .push .pop 从数组中间删除项目
【发布时间】:2020-05-01 10:28:50
【问题描述】:

我在评估考试中遇到了这个问题,最后我没通过,但我又得到了第二次机会。这是问题之一,我似乎无法理解如何解决它。 唯一允许使用的运算符是: .length() .push(x) .pop()

=== !==

=

&& ||

任务如下: 编写一个函数,将多个零序列修剪为单个零位。返回值是更新后的数组。您不允许使用另一个数组,并且您需要通过一次遍历数组来实现它(通常仅由一个循环实现)。换句话说,数组中的每个元素在程序期间应该只改变一次它的索引。

var w = [1,2,0,0,0,0,5,7,-6,0,8,0,0]; 
var n = zeroTrim(w); 
console.log(n);  //print [1,2,0,5,7,-6,0,8,0] 

我非常感谢任何帮助解决它。尤其是了解如何仅使用 .pop 和 .push 从数组中间修剪元素?

【问题讨论】:

    标签: javascript arrays function loops evaluation


    【解决方案1】:

    Pop 元素 if two zero's are adjacent else 递增 i

    # Python3 , Should be able to follow the procedure
    w = [1,2,0,0,0,0,5,7,-6,0,8,0,0,0,5]
    i=0
    while i<len(w)-1:
        # if there are two adjacent element equal to zero, pop it
        if w[i]==w[i+1]==0:
            w.pop(i)
        else:
            i+=1
    print(w) # output: [1, 2, 0, 5, 7, -6, 0, 8, 0, 5]
    

    【讨论】:

      猜你喜欢
      • 2018-07-05
      • 1970-01-01
      • 2021-10-22
      • 1970-01-01
      • 2022-11-17
      • 1970-01-01
      • 2012-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多