- Leetcode 3066. Minimum Operations to Exceed Threshold Value II
- 1. 解題思路
- 2. 代碼實現
- 題目鏈接:Leetcode 3066. Minimum Operations to Exceed Threshold Value II
1. 解題思路
這一題的話只需要排序之后按照題目條件逐一進行執行直至滿足條件即可。
唯一需要注意的是,在python當中不斷地執行pop操作復雜度過高,因此可以考慮不pop,只是平移坐標然后只添加元素或者更干脆地,使用堆排進行實現,可以有更高的執行效率。
2. 代碼實現
給出python代碼實現如下:
class Solution:def minOperations(self, nums: List[int], k: int) -> int:heapq.heapify(nums)ans = 0while nums[0] < k:x = heapq.heappop(nums)y = heapq.heappop(nums)z = x * 2 + yheapq.heappush(nums, z)ans += 1return ans
提交代碼評測得到:耗時667ms,占用內存38.4MB。