题链接:leetcode-cn.com/problems/la…
题解:
直接使用数组自身的sort方法 对所有石头的数组进行遍历,做升序处理之后,分别弹栈两次,得出a,b 差值,这样就不存在负值, 然后将差值存入数组中, 递归这个过程,判断假如出现数组1的情况 直接返回不走后续过程,否则一块石头都没剩的情况返回0
function lastStoneWeight(stones) {
if(stones.length ===1) return stones[0]
// 升序, 不会出现负数问题
stones.sort((a, b) => a-b)
if (stones.length > 1) {
let num = stones.pop() - stones.pop()
if (num) stones.push(num)
return lastStoneWeight(stones)
}
return stones.length ? stones[0] :0
}