Missing Element in Sorted Array

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;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章