LeetCode 330. Patching Array
Description
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
Example 1:
Input: nums = [1,3], n = 6
Output: 1
Explanation:
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.
Example 2:
Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].
Example 3:
Input: nums = [1,2,2], n = 5
Output: 0
描述
給定一個已排序的正整數陣列 nums,和一個正整數 n 。從 [1, n] 區間內選取任意個數字補充到 nums 中,使得 [1, n] 區間內的任何數字都可以用 nums 中某幾個數字的和來表示。請輸出滿足上述要求的最少需要補充的數字個數。
示例 1:
輸入: nums = [1,3], n = 6
輸出: 1
解釋:
根據 nums 裡現有的組合 [1], [3], [1,3],可以得出 1, 3, 4。
現在如果我們將 2 新增到 nums 中, 組合變為: [1], [2], [3], [1,3], [2,3], [1,2,3]。
其和可以表示數字 1, 2, 3, 4, 5, 6,能夠覆蓋 [1, 6] 區間裡所有的數。
所以我們最少需要新增一個數字。
示例 2:
輸入: nums = [1,5,10], n = 20
輸出: 2
解釋: 我們需要新增 [2, 4]。
示例 3:
輸入: nums = [1,2,2], n = 5
輸出: 0
思路
- 貪心演算法,每次都取最小的值把範圍擴大更大。
- 對於給定的一個數組,假設前 k 個數字的和為 tmp (前 k 個數為 num[0] ~ num[k-1]),也就是說從 0 到 tmp 的所有的數我們都可以取到。
- 我們要擴大這個範圍,如果 num[k] 比 tmp + 1大,如果這個時候直接把 num[k] 新增到陣列中,那麼 [tmp+1,num[k])之間的和是無法構造得到的。
- 於是我們將此時的邊界 tmp + 1 作為需要的新的數新增到陣列中;如果num[k] 小於等於 tmp + 1,我們直接把 num[k] 新增的陣列中擴邊界。
# -*- coding: utf-8 -*- # @Author:何睿 # @Create Date:2019-03-14 20:40:22 # @Last Modified by:何睿 # @Last Modified time: 2019-03-14 21:57:33 class Solution: def minPatches(self, nums: [int], n: int) -> int: # tmp 表示所有數字的和,count表示需要新增數字,i 為索引 # 定義[0,8) 8 為和的邊界 tmp, count, i = 0, 0, 0 # 迴圈條件 while tmp < n: # 如果 num[i] 在當前和的範圍之內,那麼把 num[i] 新增到 # 當前的和範圍內是最經濟的做法 if i < len(nums) and nums[i] <= tmp + 1: tmp += nums[i] i += 1 # 否則,我們需要把當前和的邊界的數字作為一個新的數字新增到和中 else: tmp += tmp + 1 count += 1 return count
原始碼檔案在這裡 。
©本文首發於 何睿的部落格 ,歡迎轉載,轉載需保留文章來源 ,作者資訊和本宣告.