[leetcode]330. 按要求补齐数组

题目[leetcode]330. 按要求补齐数组_第1张图片

解法

贪心算法,参考如下官方讲解:
https://leetcode-cn.com/problems/patching-array/solution/an-yao-qiu-bu-qi-shu-zu-by-leetcode/

Code

class Solution {
public:
    int minPatches(vector<int>& nums, int n) {
        long num = 1;
        int index = 0;
        int res = 0;
        
        while ( num <= n ){
            if ( index < nums.size() && nums[index] <= num ){
                num += nums[index];
                index++;
            }else{
                num += num;
                res++;
            }
        }
        
        return res;
    }
};

注:num数据类型为long,否则会超时

你可能感兴趣的:(leetcode)