zoukankan      html  css  js  c++  java
  • 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 of the whole array < 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. 

    If missing count < k, then must fall on the right side. l = mid + 1.

    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] - (n - 1 - 0) < k){
     5             return nums[n - 1] + k - missCount(nums, n - 1);
     6         }
     7         
     8         int l = 0;
     9         int r = n - 1;
    10         
    11         while(l < r){
    12             int mid = l + (r - l) / 2;
    13             if(missCount(nums, mid) < k){
    14                 l = mid + 1;
    15             }else{
    16                 r = mid;
    17             }
    18         }
    19         
    20         return nums[l - 1] + k - missCount(nums, l - 1);
    21     }
    22     
    23     private int missCount(int [] nums, int mid){
    24         return nums[mid] - nums[0] - mid;
    25     }
    26 }
  • 相关阅读:
    hdu 3746 Cyclic Nacklace
    hdu 3336 Count the string
    hdu 1358 Period
    hiho一下 第一周 最长回文子串
    KMP算法详解
    Java 之 static的使用方法(6)
    Jave 之方法-函数(5)
    Java 之数组(4)
    大数据-storm学习资料视频
    大数据-spark-hbase-hive等学习视频资料
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11902286.html
Copyright © 2011-2022 走看看