Shi*_*rsz 6 javascript arrays recursion
假设我们有一个像下一个这样的数字数组:
const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];
Run Code Online (Sandbox Code Playgroud)
目标是删除重复值,但前提是它们相邻。因此,前一个样本的预期输出应该是:
[2, 0, 2, 3, 0, 1]
Run Code Online (Sandbox Code Playgroud)
到目前为止,我设法使用递归方法几乎解决了这个问题,但由于某种我无法想象的原因,生成的结果没有返回(但是,您可以在返回条件之前的日志中看到它)。
const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];
Run Code Online (Sandbox Code Playgroud)
[2, 0, 2, 3, 0, 1]
Run Code Online (Sandbox Code Playgroud)
所以,首先也是主要的是,我想了解我的方法发生了什么,其次我对可以解决这个问题的任何其他方法(任何类型)持开放态度。
以防万一有人感兴趣,我终于以这种方式使用递归解决了这个问题。我知道过滤器解决方案简短而优雅,但我正在通过递归训练解决方案。
const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];
const remAdjDups = (arr, output = []) =>
{
if (!arr.length)
{
console.log("Result before return: ", output);
return output;
}
if (arr[0] === arr[1])
{
arr.splice(1, 1);
remAdjDups(arr, output);
}
else
{
remAdjDups(arr.slice(1), output.concat(arr[0]));
}
}
let out = remAdjDups(input.slice());
console.log("output: ", out);Run Code Online (Sandbox Code Playgroud)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}Run Code Online (Sandbox Code Playgroud)
关于您的解决方案,只需添加return之前remAdjDups(arr...
聚苯乙烯
我为此使用了Array.prototype.filter
const input = [2, 2, 0, 2, 3, 3, 0, 0, 1, 1];
const result = input.filter((i,idx) => input[idx-1] !== i)
console.log(result)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1090 次 |
| 最近记录: |