LeetCode Patching Array

暑假实习太累了,没时间刷刷题。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;
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值