Leetcode - Patching Array
My code:
public class Solution {
public int minPatches(int[] nums, int n) {
long max = 0;
int c = 0;
for (int i = 0; max < n;) {
if (i >= nums.length || max < nums[i] - 1) {
max += max + 1;
c++;
}
else {
max += nums[i];
i++;
}
}
return c;
}
}
我覺得這個思想還是很巧妙的。
max 表示的是當前數字下,我能構成的最大數字,並且最小數字和最大數字之間是連續的。
如果 max < nums[i] - 1,
這表示 (max, nums[i]) 這段區域,有些數字我不能表示,就直接跳到了 nums[i]
這裡,我就需要 patch 了
但是,我patch的時候,也得注意,用最少的patch,把(preMax, currMax) 連續得連線起來。
那麼,我得patch (max + 1) 這個數。
這樣的話, [max, max + max + 1] 這段區域內,所有的數字,我都可以表示
然後我一次次得累加,直到 max >= nums[i] - 1
同理, max >= n
Anyway, Good luck, Richardo! -- 10/08/2016
相關文章
- LeetCode Patching Array All In OneLeetCode
- Leetcode Sort ArrayLeetCode
- Rotate Array@LeetCodeLeetCode
- LeetCode-Rotate ArrayLeetCode
- LeetCode-Shuffle an ArrayLeetCode
- LeetCode-Pathcing ArrayLeetCode
- Leetcode Search in Rotated Sorted ArrayLeetCode
- Leetcode Merge Sorted ArrayLeetCode
- leetcode刷題--Rotate ArrayLeetCode
- LeetCode:Product of Array Except SelfLeetCode
- LeetCode Kth Largest Element in an ArrayLeetCode
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- Leetcode Search in Rotated Sorted Array IILeetCode
- leetcode Remove Duplicates from Sorted ArrayLeetCodeREM
- Leetcode-Merge Sorted ArrayLeetCode
- Leetcode-Search in Rotated Sorted ArrayLeetCode
- Search in Rotated Sorted Array leetcode javaLeetCodeJava
- Oracle opatch - offline patching 及 online patchingOracle
- oracle叢集patchingOracle
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- LeetCode Shuffle an Array(打亂陣列)LeetCode陣列
- [LeetCode] 852. Peak Index in a Mountain ArrayLeetCodeIndexAI
- LeetCode之Sort Array By Parity(Kotlin)LeetCodeKotlin
- Leetcode 26 Remove Duplicates from Sorted ArrayLeetCodeREM
- Leetcode 442. Find All Duplicates in an ArrayLeetCode
- Leetcode 88. Merge Sorted ArrayLeetCode
- [leetcode] 1394. Find Lucky Integer in an ArrayLeetCode
- leetcode33_Search in Rotated Sorted ArrayLeetCode
- Leetcode[421] Maximum XOR of Two Numbers in an ArrayLeetCode
- LeetCode 350 [Intersection of Two Array II]LeetCode
- LeetCode-Search in Rotated Sorted Array IILeetCode
- Leetcode Remove Duplicates from Sorted Array IILeetCodeREM
- Leetcode-Convert Sorted Array to BSTLeetCode
- Leetcode-Remove Duplicates from Sorted ArrayLeetCodeREM
- Median of Two Sorted Array leetcode javaLeetCodeJava
- Remove Duplicates from Sorted Array leetcode javaREMLeetCodeJava
- Search in Rotated Sorted Array II leetcode javaLeetCodeJava
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++