码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 1060. Missing Element in Sorted Array

时间:2019-11-21 09:55:39      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:art   java   must   upd   uniq   first   -o   missing   lse   

原题链接在这里: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 }

 

LeetCode 1060. Missing Element in Sorted Array

标签:art   java   must   upd   uniq   first   -o   missing   lse   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11902286.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!