我的js算法爬坑之旅-最后一块石头的重量

76 阅读1分钟

第八十四天:力扣1046题,最后一块石头的重量

地址:leetcode-cn.com/problems/la…

思路:sort排序,然后依次取出最后两块最大的值进行相减,不为0的情况下放入数组继续排序即可。

var lastStoneWeight = function(stones) {
  stones.sort((a, b) => a - b);
  while(stones.length > 1)
  {
    const a = stones.pop();
    const b = stones.pop();
    const c = a - b;
    if(c != 0)
    {
      stones.push(c);
      stones.sort((a, b) => a - b);
    }
    if(c === 0 && stones.length === 0)
    {
      return 0;
    }
  }
  return stones[0];
};

执行用时:92 ms, 在所有 JavaScript 提交中击败了29.17%的用户

内存消耗:39.1 MB, 在所有 JavaScript 提交中击败了61.40%的用户