LC 1060
Input: nums = [4,7,9,10], k = 3.
We can find the first index where the missing elements >= k. Here we can find index = 2 is the min index where we have missing elements = A[2] - A[0] - (2 - 0) = 3 >= k = 3, then the kth missing number is after A[1] = 7.
Find left bound where A[mid] - A[0] - mid >= k, right must be initialized to n here because the result can lie outside [0, n).
For ex, A[2] - A[0] - (2 - 0) = 1 < k = 3.
Input: nums = [1,2,4], k = 3
Output: 6
public int missingElement(int[] A, int k) {
int left = 0, right = A.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (A[mid] - A[0] - mid < k) {
left = mid + 1;
} else {
right = mid;
}
}
return A[0] + k + left - 1;
}
复制代码
Input: nums = [4,7,9,10], k = 3.
We can also find the last index where the missing elements < k. Here we can find index = 1 is the max index where we have missing elements = A[1] - A[0] - 1 - 0 = 2 < k = 3, then the kth missing number is after A[1] = 7.
Find right bound where A[mid] - A[0] - mid < k
public int missingElement(int[] A, int k) {
int left = 0, right = A.length - 1;
while (left < right) {
int mid = right - (right - left) / 2;
if (A[mid] - A[0] - mid < k) {
left = mid;
} else {
right = mid - 1;
}
}
return A[0] + k + left;
}
复制代码
Because finally we need to locate a subarray of two elements where l = r - 1, and the solution will be in this range (A[l], A[r]), which is A[l] + updated k.
public int missingElement(int[] A, int k) {
int left = 0, right = A.length - 1;
int missing = A[right] - A[left] - (right - left);