leetcode 330. Patching Array | 1798. Maximum Number of Consecutive Values You Can Make

向右看齐 2022-09-09 06:48 216阅读 0赞

1798. Maximum Number of Consecutive Values You Can Make | 1798. 你能构造出连续值的最大数目

https://leetcode.com/problems/maximum-number-of-consecutive-values-you-can-make/
在这里插入图片描述

题解

这题没有套路。。

随手就是一个 O(2^n) 暴力,妥妥的超时了。看了 hint 没看懂,后来看了答案:

参考:https://leetcode-cn.com/problems/maximum-number-of-consecutive-values-you-can-make/solution/ni-neng-gou-zao-chu-lian-xu-zhi-de-zui-d-hlxf/
在这里插入图片描述

  1. class Solution {
  2. public int getMaximumConsecutive(int[] coins) {
  3. Arrays.sort(coins);
  4. int end = 0;
  5. for (int coin : coins) {
  6. if (coin <= end + 1) end += coin;
  7. else break;
  8. }
  9. return end + 1;
  10. }
  11. }

在这里插入图片描述


leetcode 330. Patching Array | 330. 按要求补齐数组

https://leetcode.com/problems/patching-array/
在这里插入图片描述

题解

做过上一道 330. Patching Array 之后,这个题的思路就简单了。

当连续区间 0~end 和下一个 num 不连续的时候,用 end+1 来填充,然后更新 end,直到 end 能和下一个 num 毗邻为止。

  1. class Solution {
  2. public int minPatches(int[] nums, int n) {
  3. int count = 0;
  4. long end = 0;
  5. for (long num : nums) {
  6. while (num > end + 1) {
  7. count += 1;
  8. end += (end + 1);
  9. if (end >= n) return count; // 满足条件,随时跑路!
  10. }
  11. end += num;
  12. if (end >= n) return count; // 满足条件,随时跑路!
  13. }
  14. // 收尾
  15. while (n > end + 1) {
  16. count += 1;
  17. end += (end + 1);
  18. }
  19. return count;
  20. }
  21. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,216人围观)

还没有评论,来说两句吧...

相关阅读