LeetCode 1060. Missing Element in Sorted Array

原题链接在这里:https://leetcode.com/problems/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.

Note:

  1. 1 <= A.length <= 50000
  2. 1 <= A[i] <= 1e7
  3. 1 <= K <= 1e8

题解:

If the missing numbers count < k, then missing number must be after nums[n-1]. 

res = nums[n-1] + missingCount.

Otherwise, need to find out the starting index to calculate the missing number.

Use binary search to have mid as candidate. 

Now missing numbers count between numd[l] and nums[mid] is nums[mid] - nums[l]-(mid-l).

If this count >= k, then starting index must not fall into (l, r], including r.

Otherwise, starting index fall into right side. But need to update k as k-missingCount.

Time Complexity: O(logn). n = nums.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int missingElement(int[] nums, int k) {
 3         int n = nums.length;
 4         if(nums[n-1]-nums[0]+1-n < k){
 5             return nums[n-1] + k-(nums[n-1]-nums[0]+1-n);
 6         }
 7         
 8         int l = 0;
 9         int r = n-1;
10         while(l<r-1){
11             int mid = l + (r-l)/2;
12             int missingCount = nums[mid]-nums[l]-(mid-l);
13             if(missingCount >= k){
14                 // When missingCount <= k, starting index to calculate must not fall into (l, r].
15                 r = mid;
16             }else{
17                 l = mid;
18                 k -= missingCount;
19             }
20         }
21         
22         return nums[l]+k;
23     }
24 }

猜你喜欢

转载自www.cnblogs.com/Dylan-Java-NYC/p/11902286.html