Given a sorted array A
of unique numbers, find the K-th
missing number starting from the leftmost number of the array.
Example 1:
Input: A = [4,7,9,10], K = 1 Output: 5 Explanation: The first missing number is 5.
Example 2:
Input: A = [4,7,9,10], K = 3 Output: 8 Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.
Example 3:
Input: A = [1,2,4], K = 3 Output: 6 Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6.
思路:这题很牛逼,把missing number的个数,用来做binary search的标准。
主要考点就是:missing number 的个数是: nums[end] - nums[start] - (end - start);
4, (5,6) , 7 -- > 7 - 4 - (1 - 0) = 3 - 1 = 2;
注意:If k > missing, the result will be larger than the rightmost one in the array, we return nums[right] + k - missing.
class Solution {
public int missingElement(int[] nums, int k) {
if(nums == null || nums.length == 0) {
return 0;
}
int start = 0; int end = nums.length - 1;
int missing = nums[end] - nums[start] - (end - start);
if(missing < k) {
return nums[end] + (k - missing);
}
while(start + 1 < end) {
int mid = start + (end - start) / 2;
int missingLeft = nums[mid] - nums[start] - (mid - start);
if(missingLeft >= k) {
end = mid;
} else {
// missingLeft < k;
start = mid;
k -= missingLeft;
}
}
return nums[start] + k;
}
}