1060. Missing Element in Sorted Array

Given an integer array nums which is sorted in ascending order and all of its elements are unique and given also an integer k, return the kth missing number starting from the leftmost number of the array.

 

Example 1:

Input: nums = [4,7,9,10], k = 1
Output: 5
Explanation: The first missing number is 5.

Example 2:

Input: nums = [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: nums = [1,2,4], k = 3
Output: 6
Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6.
 1 class Solution {
 2 // The key is to understand that the number of the missing numbers between nums[left] and nums[right] is nums[right] - nums[left] - (right - left).
 3 // Be careful to check in the beginning: If k > missing, the result will be larger than the rightmost one in the array, we return nums[right] + k - missing.
 4 
 5     public int missingElement(int[] nums, int k) {
 6         if (nums == null || nums.length == 0) return 0;
 7         int left = 0, right = nums.length - 1;
 8         int missing = nums[right] - nums[left] - (right - left);
 9         if (missing < k) return nums[right] + k - missing;
10         // we need to reduce to 2 numbers in the array
11         // [1,2,4] [1,3,4]. Both missing 1 number, but we need to continue to narrow
12         // down.
13         while (left + 1 < right) {
14             int mid = left + (right - left) / 2;
15             int missingLeft = nums[mid] - nums[left] - (mid - left);
16             if (missingLeft >= k) {
17                 right = mid;
18             } else {
19                 k -= missingLeft;
20                 left = mid;
21             }
22         }
23         return nums[left] + k;
24     }
25 }

 

posted @ 2021-03-29 02:33  北叶青藤  阅读(51)  评论(0编辑  收藏  举报