暑假实习太累了,没时间刷刷题。return offer到手,但是离开学还有一段时间,接着来刷!
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.
Solution:
暴力解法肯定都会,但是既然是hard,肯定不会那么简单就过的。
这么考虑,假设我把nums数组一个个扫过来,扫完第index个,假设前面都已经把miss的patch补上,那么我们最多能表示的范围应该是[1, max=sum(index)+sum(patch)],所以对于nums[index+1], 如果小于这个max+1,那么我可以把它归并到前面的max中,也就是max+=nums[index+1];否则我就要加一个数字是max+1,然后max+=max+1。如此一直循环,一直到max>=n为止。(有点DP状态表示的感觉)
import java.util.*;
public class Solution {
public int minPatches(int[] nums, int n) {
int ans = 0;
long max = 0;
int index = 0;
int length = nums.length;
while (max < n) {
if (index < length && nums[index] <= max + 1)
max = max + nums[index++];
else {
ans++;
max = max * 2l + 1l;
}
}
return ans;
}
}