js(61)~[1046] 最后一块石头的重量

147 阅读1分钟

力扣本题传送门

自己尝试了1个小时,还是该不对,只好去看题解了,我自己刚开始写的错误代码如下:

/**
 * @param {number[]} stones
 * @return {number}
 */
var lastStoneWeight = function(stones) {
    const arr = stones;
    // let [afterArr, max1] = getMax(arr);
    let max1 = getMax(arr);
    let max2 = getMax(arr);
    // let [arr2, max2] = getMax(afterArr);
    // console.log(arr, max1,max2, stones);
    console.log(arr, max1, max2);

    if(arr.length >= 1) {
    // 如果两个相同 则两个都消失 进入下一轮
        if(max1 !== max2) {
             arr.push(max1-max2)   
            }
            lastStoneWeight(arr);
    }
    let res = arr[0];
    if(!res) {
        console.log(max1,'1-2',max2)
        if(max1 && max2) {
            res =  Math.abs(max1 - max2);
        } else {
            res = max1 ;
        }
    }
    console.log('res--', res)
    return res;
    
};

// 获取数组中最大元素和 去掉最大元素后的新数组
var getMax = function(arr) {
    let poivt = arr[0];
    let poivtInx = 0;
    for(const i in arr) {
        const num = arr[i];
        // console.log(num,i)
        if(poivt <= num) {
            poivt = num;
            poivtInx = i;
        }
    }
   arr.splice(poivtInx, 1);
    // console.log(poivt, arr)

    return poivt;
    // return [arr, poivt];
}

看完题解,发现我自己写的也是递归方法,只是比较麻烦判断的条件比较多,好的是我这样写也能成功,下面图片跟上面的一样,只是19行少了return

image.png

总结:

我自己写的迭代,比较麻烦,是我第一没有想到,sort按照大小排序以后,最后的两个就是最大和次大,第二,最后返回的时候做了一堆没有多大用处的判断,还是我想太多了,把递归后的结果想的复杂了

更优秀的解法如下

挑了2中好理解的,如下

var lastStoneWeight = function (stones) {
	stones.sort((a, b) => a - b);
	// 方法一 迭代
	// while (stones.length > 1) {
	// 	const temp = stones.pop() - stones.pop();
	// 	if (temp) {
	// 		stones.push(temp);
	// 		stones.sort((a, b) => a - b);
	// 	}
	// }
	// 方法二 递归
	if (stones.length > 1) {
		const temp = stones.pop() - stones.pop();
		if (temp) {
			stones.push(temp);
		}
		return lastStoneWeight(stones);

	}

	return stones.length ? stones[0] : 0;
};