英文原题
Given an array of integers target. From a starting array, A consisting of all 1’s, you may perform the following procedure :
- let x be the sum of all elements currently in your array.
- choose index i, such that 0 <= i < target.size and set the value of A at index i to x.
- You may repeat this procedure as many times as needed.
Return True if it is possible to construct the target array from A otherwise return False.
Example
1 | Input: target = [9,3,5] |
分析
这道题很巧妙的运用了逆向思维的方法,从target开始,一步步推导前面的一个数组会是什么。比如例子里给的[9,3,5] 它的前一个数组必然是 [1,3,5],因为前一个数组的和所变的数一定是最大的那个数,这样问题就变成了能不能从target变回1数组。 推导过程: [9,3,5] => [9 – (3+5), 3, 5] => [1, 3, 5] => [1, 3, 5 – (1+3)] => [1, 3, 1] => [1, 3 – (1+1), 1] => [1,1,1] done 参考了花花酱的做法,可以看这里
python 代码
1 | class Solution: |
用到了heapq,这里要注意python的heapq可以写成最大堆,但是最大堆没法push,我这里用的是heapreplace直接改,想要push的话最好还是用最小堆,然后取负值,用的时候在反过来就可以了。