我有一个关于这个问题的解决方案的问题。它有效,但我的问题是为什么我必须写
stones = stones.slice(0 ,length - 2)
Run Code Online (Sandbox Code Playgroud)
代替
stones.slice(0 ,length - 2)
Run Code Online (Sandbox Code Playgroud)
像 sort() 和 push 没有它的工作。
var lastStoneWeight = function (stones) {
stones.sort((a, b) => a - b);
let length = stones.length
if(length <= 1) return stones
let replace = stones[length - 1] - stones[length - 2]
stones = stones.slice(0 ,length - 2) // <----- HERE
stones.push(replace)
if (stones.length > 1) return lastStoneWeight(stones)
return stones
};
console.log(lastStoneWeight([8,10,4])); //return [2]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
82 次 |
| 最近记录: |