📜  排序数组中的第k个缺失元素

📅  最后修改于: 2021-04-29 02:02:39             🧑  作者: Mango

给定一个递增的序列a [] ,我们需要在递增的序列中找到第K个缺失的连续元素,该元素在序列中不存在。如果没有第k个缺失元素,则输出-1。

例子 :

Input : a[] = {2, 3, 5, 9, 10};   
        k = 1;
Output : 4
Explanation: Missing Element in the increasing 
sequence are {4, 6, 7, 8}. So k-th missing element
is 4

Input : a[] = {2, 3, 5, 9, 10, 11, 12};       
        k = 4;
Output : 8
Explanation: missing element in the increasing 
sequence are {4, 6, 7, 8}  so k-th missing 
element is 8

方法1:开始遍历数组元素,对于每个元素,检查下一个元素是否连续,如果不连续,则取这两个元素之间的差,并检查差是否大于或等于给定的k,然后计算ans = a [i] + count,否则迭代下一个元素。

C++
#include 
using namespace std;
 
// Function to find k-th
// missing element
int missingK(int a[], int k,
             int n)
{
    int difference = 0,
        ans = 0, count = k;
    bool flag = 0;
     
    // interating over the array
    for(int i = 0 ; i < n - 1; i++)
    {  
        difference = 0;
         
        // check if i-th and
        // (i + 1)-th element
        // are not consecutive
        if ((a[i] + 1) != a[i + 1])
        {
             
            // save their difference
            difference +=
                (a[i + 1] - a[i]) - 1;
             
            // check for difference
            // and given k
            if (difference >= count)
                {
                    ans = a[i] + count;
                    flag = 1;
                    break;
                }
            else
                count -= difference;
        }
    }
     
    // if found
    if(flag)
        return ans;
    else
        return  -1;
}
 
// Driver code
int main()
{
    // Input array
    int a[] = {1, 5, 11, 19};
     
    // k-th missing element
    // to be found in the array
    int k = 11;
    int n = sizeof(a) / sizeof(a[0]);
     
    // calling function to
    // find missing element
    int missing = missingK(a, k, n);
     
    cout << missing << endl;
     
    return 0;
}


Java
// Java program to check for
// even or odd
import java.io.*;
import java.util.*;
  
public class GFG {
      
    // Function to find k-th
    // missing element
    static int missingK(int []a, int k,
                                 int n)
    {
        int difference = 0,
            ans = 0, count = k;
        boolean flag = false;
          
        // interating over the array
        for(int i = 0 ; i < n - 1; i++)
        {
            difference = 0;
              
            // check if i-th and
            // (i + 1)-th element
            // are not consecutive
            if ((a[i] + 1) != a[i + 1])
            {
                  
                // save their difference
                difference +=
                    (a[i + 1] - a[i]) - 1;
                  
                // check for difference
                // and given k
                if (difference >= count)
                    {
                        ans = a[i] + count;
                        flag = true;
                        break;
                    }
                else
                    count -= difference;
            }
        }
          
        // if found
        if(flag)
            return ans;
        else
            return -1;
    }
      
    // Driver code
    public static void main(String args[])
    {
          
        // Input array
        int []a = {1, 5, 11, 19};
          
        // k-th missing element
        // to be found in the array
        int k = 11;
        int n = a.length;
          
        // calling function to
        // find missing element
        int missing = missingK(a, k, n);
          
        System.out.print(missing);
    }
  
}
  
// This code is contributed by
// Manish Shaw (manishshaw1)


Python3
# Function to find k-th
# missing element
def missingK(a, k, n) :
 
    difference = 0
    ans = 0
    count = k
    flag = 0
     
    # interating over the array
    for i in range (0, n-1) :
        difference = 0
         
        # check if i-th and
        # (i + 1)-th element
        # are not consecutive
        if ((a[i] + 1) != a[i + 1]) :
         
             
            # save their difference
            difference += (a[i + 1] - a[i]) - 1
             
            # check for difference
            # and given k
            if (difference >= count) :
                    ans = a[i] + count
                    flag = 1
                    break
            else :
                count -= difference    
     
    # if found
    if(flag) :
        return ans
    else :
        return -1
 
# Driver code
# Input array
a = [1, 5, 11, 19]
 
# k-th missing element
# to be found in the array
k = 11
n = len(a)
 
# calling function to
# find missing element
missing = missingK(a, k, n)
 
print(missing)
 
# This code is contributed by
# Manish Shaw (manishshaw1)


C#
// C# program to check for
// even or odd
using System;
using System.Collections.Generic;
 
class GFG {
     
    // Function to find k-th
    // missing element
    static int missingK(int []a, int k,
                                 int n)
    {
        int difference = 0,
            ans = 0, count = k;
        bool flag = false;
         
        // interating over the array
        for(int i = 0 ; i < n - 1; i++)
        {
            difference = 0;
             
            // check if i-th and
            // (i + 1)-th element
            // are not consecutive
            if ((a[i] + 1) != a[i + 1])
            {
                 
                // save their difference
                difference +=
                    (a[i + 1] - a[i]) - 1;
                 
                // check for difference
                // and given k
                if (difference >= count)
                    {
                        ans = a[i] + count;
                        flag = true;
                        break;
                    }
                else
                    count -= difference;
            }
        }
         
        // if found
        if(flag)
            return ans;
        else
            return -1;
    }
     
    // Driver code
    public static void Main()
    {
         
        // Input array
        int []a = {1, 5, 11, 19};
         
        // k-th missing element
        // to be found in the array
        int k = 11;
        int n = a.Length;
         
        // calling function to
        // find missing element
        int missing = missingK(a, k, n);
         
        Console.Write(missing);
    }
 
}
 
// This code is contributed by
// Manish Shaw (manishshaw1)


PHP
= $count)
                {
                    $ans = $a[$i] + $count;
                    $flag = 1;
                    break;
                }
            else
                $count -= $difference;
        }
    }
     
    // if found
    if($flag)
        return $ans;
    else
        return -1;
}
 
// Driver Code
 
// Input array
$a = array(1, 5, 11, 19);
 
// k-th missing element
// to be found in the array
$k = 11;
$n = count($a);
 
// calling function to
// find missing element
$missing = missingK($a, $k, $n);
 
echo $missing;
 
// This code is contributed by Manish Shaw
// (manishshaw1)
?>


Javascript


C++
// CPP program for above approach
#include 
#include 
using namespace std;
 
// Function to find
// kth missing number
int missingK(vector& arr, int k)
{
  int n = arr.size();
  int l = 0, u = n - 1, mid;
   
  while(l <= u)
  {
    mid = (l + u)/2;
     
    int numbers_less_than_mid = arr[mid] -
                                    (mid + 1);
     
    // If the total missing number
    // count is equal to k we can iterate
    // backwards for the first missing number
    // and that will be the answer.
    if(numbers_less_than_mid == k)
    {
       
      // To further optimize we check
      // if the previous element's
      // missing number count is equal
      // to k. Eg: arr = [4,5,6,7,8]
      // If you observe in the example array,
      // the total count of missing numbers for all
      // the indices are same, and we are
      // aiming to narrow down the
      // search window and achieve O(logn)
      // time complexity which
      // otherwise would've been O(n).
      if(mid > 0 && (arr[mid - 1] - (mid)) == k)
      {
        u = mid - 1;
        continue;
      }
      // Else we return arr[mid] - 1.
      return arr[mid]-1;
    }
     
    // Here we appropriately
    // narrow down the search window.
    if(numbers_less_than_mid < k)
    {
      l = mid + 1;
    }
    else if(k < numbers_less_than_mid)
    {
      u = mid - 1;
    }
  }
   
  // In case the upper limit is -ve
  // it means the missing number set
  // is 1,2,..,k and hence we directly return k.
  if(u < 0)
    return k;
   
  // Else we find the residual count
  // of numbers which we'd then add to
  // arr[u] and get the missing kth number.
  int less = arr[u] - (u + 1);
  k -= less;
   
  // Return arr[u] + k
  return arr[u] + k;
}
 
// Driver Code
int main()
{
    vector arr = {2,3,4,7,11};
    int k = 5;
   
    // Function Call
    cout <<"Missing kth number = "<<
                        missingK(arr, k)<


Java
// Java program for above approach
public class GFG
{
 
  // Function to find
  // kth missing number
  static int missingK(int[] arr, int k)
  {
    int n = arr.length;
    int l = 0, u = n - 1, mid;   
    while(l <= u)
    {
      mid = (l + u)/2;       
      int numbers_less_than_mid = arr[mid] -
        (mid + 1);
 
      // If the total missing number
      // count is equal to k we can iterate
      // backwards for the first missing number
      // and that will be the answer.
      if(numbers_less_than_mid == k)
      {
 
        // To further optimize we check
        // if the previous element's
        // missing number count is equal
        // to k. Eg: arr = [4,5,6,7,8]
        // If you observe in the example array,
        // the total count of missing numbers for all
        // the indices are same, and we are
        // aiming to narrow down the
        // search window and achieve O(logn)
        // time complexity which
        // otherwise would've been O(n).
        if(mid > 0 && (arr[mid - 1] - (mid)) == k)
        {
          u = mid - 1;
          continue;
        }
 
        // Else we return arr[mid] - 1.
        return arr[mid] - 1;
      }
 
      // Here we appropriately
      // narrow down the search window.
      if(numbers_less_than_mid < k)
      {
        l = mid + 1;
      }
      else if(k < numbers_less_than_mid)
      {
        u = mid - 1;
      }
    }
 
    // In case the upper limit is -ve
    // it means the missing number set
    // is 1,2,..,k and hence we directly return k.
    if(u < 0)
      return k;
 
    // Else we find the residual count
    // of numbers which we'd then add to
    // arr[u] and get the missing kth number.
    int less = arr[u] - (u + 1);
    k -= less;
 
    // Return arr[u] + k
    return arr[u] + k;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] arr = {2,3,4,7,11};
    int k = 5;
 
    // Function Call
    System.out.println("Missing kth number = "+ missingK(arr, k));
  }
}
 
// This code is contributed by divyesh072019.


Python3
# Python3 program for above approach
 
# Function to find
# kth missing number
def missingK(arr, k):
  n = len(arr)
  l = 0
  u = n - 1
  mid = 0
  while(l <= u):
    mid = (l + u)//2;
    numbers_less_than_mid = arr[mid] - (mid + 1);
     
    # If the total missing number
    # count is equal to k we can iterate
    # backwards for the first missing number
    # and that will be the answer.
    if(numbers_less_than_mid == k):
       
      # To further optimize we check
      # if the previous element's
      # missing number count is equal
      # to k. Eg: arr = [4,5,6,7,8]
      # If you observe in the example array,
      # the total count of missing numbers for all
      # the indices are same, and we are
      # aiming to narrow down the
      # search window and achieve O(logn)
      # time complexity which
      # otherwise would've been O(n).
      if(mid > 0 and (arr[mid - 1] - (mid)) == k):   
        u = mid - 1;
        continue;
       
      # Else we return arr[mid] - 1.
      return arr[mid]-1;
       
    # Here we appropriately
    # narrow down the search window.
    if(numbers_less_than_mid < k):   
      l = mid + 1;
    elif(k < numbers_less_than_mid):
      u = mid - 1;
 
  # In case the upper limit is -ve
  # it means the missing number set
  # is 1,2,..,k and hence we directly return k.
  if(u < 0):
    return k;
   
  # Else we find the residual count
  # of numbers which we'd then add to
  # arr[u] and get the missing kth number.
  less = arr[u] - (u + 1);
  k -= less;
   
  # Return arr[u] + k
  return arr[u] + k;
 
# Driver Code
if __name__=='__main__':
 
    arr = [2,3,4,7,11];
    k = 5;
   
    # Function Call
    print("Missing kth number = "+ str(missingK(arr, k)))
     
# This code is contributed by rutvik_56.


C#
// C# program for above approach
using System;
class GFG {
     
    // Function to find
    // kth missing number
    static int missingK(int[] arr, int k)
    {
      int n = arr.Length;
      int l = 0, u = n - 1, mid;
        
      while(l <= u)
      {
        mid = (l + u)/2;
          
        int numbers_less_than_mid = arr[mid] -
                                        (mid + 1);
          
        // If the total missing number
        // count is equal to k we can iterate
        // backwards for the first missing number
        // and that will be the answer.
        if(numbers_less_than_mid == k)
        {
            
          // To further optimize we check
          // if the previous element's
          // missing number count is equal
          // to k. Eg: arr = [4,5,6,7,8]
          // If you observe in the example array,
          // the total count of missing numbers for all
          // the indices are same, and we are
          // aiming to narrow down the
          // search window and achieve O(logn)
          // time complexity which
          // otherwise would've been O(n).
          if(mid > 0 && (arr[mid - 1] - (mid)) == k)
          {
            u = mid - 1;
            continue;
          }
           
          // Else we return arr[mid] - 1.
          return arr[mid] - 1;
        }
          
        // Here we appropriately
        // narrow down the search window.
        if(numbers_less_than_mid < k)
        {
          l = mid + 1;
        }
        else if(k < numbers_less_than_mid)
        {
          u = mid - 1;
        }
      }
        
      // In case the upper limit is -ve
      // it means the missing number set
      // is 1,2,..,k and hence we directly return k.
      if(u < 0)
        return k;
        
      // Else we find the residual count
      // of numbers which we'd then add to
      // arr[u] and get the missing kth number.
      int less = arr[u] - (u + 1);
      k -= less;
        
      // Return arr[u] + k
      return arr[u] + k;
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = {2,3,4,7,11};
    int k = 5;
    
    // Function Call
    Console.WriteLine("Missing kth number = "+ missingK(arr, k));
  }
}
 
// This code is contributed by divyeshrabadiya07.


输出
14

时间复杂度: O(n),其中n是数组中元素的数量。

方法二:

应用二进制搜索。由于对数组进行了排序,我们可以在任何给定的索引处找到多少个缺失的数字,如arr [index] –(index + 1)。我们将利用这些知识并应用二进制搜索来缩小搜索范围,以找到从中获取缺失数更容易的索引。

下面是上述方法的实现:

C++

// CPP program for above approach
#include 
#include 
using namespace std;
 
// Function to find
// kth missing number
int missingK(vector& arr, int k)
{
  int n = arr.size();
  int l = 0, u = n - 1, mid;
   
  while(l <= u)
  {
    mid = (l + u)/2;
     
    int numbers_less_than_mid = arr[mid] -
                                    (mid + 1);
     
    // If the total missing number
    // count is equal to k we can iterate
    // backwards for the first missing number
    // and that will be the answer.
    if(numbers_less_than_mid == k)
    {
       
      // To further optimize we check
      // if the previous element's
      // missing number count is equal
      // to k. Eg: arr = [4,5,6,7,8]
      // If you observe in the example array,
      // the total count of missing numbers for all
      // the indices are same, and we are
      // aiming to narrow down the
      // search window and achieve O(logn)
      // time complexity which
      // otherwise would've been O(n).
      if(mid > 0 && (arr[mid - 1] - (mid)) == k)
      {
        u = mid - 1;
        continue;
      }
      // Else we return arr[mid] - 1.
      return arr[mid]-1;
    }
     
    // Here we appropriately
    // narrow down the search window.
    if(numbers_less_than_mid < k)
    {
      l = mid + 1;
    }
    else if(k < numbers_less_than_mid)
    {
      u = mid - 1;
    }
  }
   
  // In case the upper limit is -ve
  // it means the missing number set
  // is 1,2,..,k and hence we directly return k.
  if(u < 0)
    return k;
   
  // Else we find the residual count
  // of numbers which we'd then add to
  // arr[u] and get the missing kth number.
  int less = arr[u] - (u + 1);
  k -= less;
   
  // Return arr[u] + k
  return arr[u] + k;
}
 
// Driver Code
int main()
{
    vector arr = {2,3,4,7,11};
    int k = 5;
   
    // Function Call
    cout <<"Missing kth number = "<<
                        missingK(arr, k)<

Java

// Java program for above approach
public class GFG
{
 
  // Function to find
  // kth missing number
  static int missingK(int[] arr, int k)
  {
    int n = arr.length;
    int l = 0, u = n - 1, mid;   
    while(l <= u)
    {
      mid = (l + u)/2;       
      int numbers_less_than_mid = arr[mid] -
        (mid + 1);
 
      // If the total missing number
      // count is equal to k we can iterate
      // backwards for the first missing number
      // and that will be the answer.
      if(numbers_less_than_mid == k)
      {
 
        // To further optimize we check
        // if the previous element's
        // missing number count is equal
        // to k. Eg: arr = [4,5,6,7,8]
        // If you observe in the example array,
        // the total count of missing numbers for all
        // the indices are same, and we are
        // aiming to narrow down the
        // search window and achieve O(logn)
        // time complexity which
        // otherwise would've been O(n).
        if(mid > 0 && (arr[mid - 1] - (mid)) == k)
        {
          u = mid - 1;
          continue;
        }
 
        // Else we return arr[mid] - 1.
        return arr[mid] - 1;
      }
 
      // Here we appropriately
      // narrow down the search window.
      if(numbers_less_than_mid < k)
      {
        l = mid + 1;
      }
      else if(k < numbers_less_than_mid)
      {
        u = mid - 1;
      }
    }
 
    // In case the upper limit is -ve
    // it means the missing number set
    // is 1,2,..,k and hence we directly return k.
    if(u < 0)
      return k;
 
    // Else we find the residual count
    // of numbers which we'd then add to
    // arr[u] and get the missing kth number.
    int less = arr[u] - (u + 1);
    k -= less;
 
    // Return arr[u] + k
    return arr[u] + k;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] arr = {2,3,4,7,11};
    int k = 5;
 
    // Function Call
    System.out.println("Missing kth number = "+ missingK(arr, k));
  }
}
 
// This code is contributed by divyesh072019.

Python3

# Python3 program for above approach
 
# Function to find
# kth missing number
def missingK(arr, k):
  n = len(arr)
  l = 0
  u = n - 1
  mid = 0
  while(l <= u):
    mid = (l + u)//2;
    numbers_less_than_mid = arr[mid] - (mid + 1);
     
    # If the total missing number
    # count is equal to k we can iterate
    # backwards for the first missing number
    # and that will be the answer.
    if(numbers_less_than_mid == k):
       
      # To further optimize we check
      # if the previous element's
      # missing number count is equal
      # to k. Eg: arr = [4,5,6,7,8]
      # If you observe in the example array,
      # the total count of missing numbers for all
      # the indices are same, and we are
      # aiming to narrow down the
      # search window and achieve O(logn)
      # time complexity which
      # otherwise would've been O(n).
      if(mid > 0 and (arr[mid - 1] - (mid)) == k):   
        u = mid - 1;
        continue;
       
      # Else we return arr[mid] - 1.
      return arr[mid]-1;
       
    # Here we appropriately
    # narrow down the search window.
    if(numbers_less_than_mid < k):   
      l = mid + 1;
    elif(k < numbers_less_than_mid):
      u = mid - 1;
 
  # In case the upper limit is -ve
  # it means the missing number set
  # is 1,2,..,k and hence we directly return k.
  if(u < 0):
    return k;
   
  # Else we find the residual count
  # of numbers which we'd then add to
  # arr[u] and get the missing kth number.
  less = arr[u] - (u + 1);
  k -= less;
   
  # Return arr[u] + k
  return arr[u] + k;
 
# Driver Code
if __name__=='__main__':
 
    arr = [2,3,4,7,11];
    k = 5;
   
    # Function Call
    print("Missing kth number = "+ str(missingK(arr, k)))
     
# This code is contributed by rutvik_56.

C#

// C# program for above approach
using System;
class GFG {
     
    // Function to find
    // kth missing number
    static int missingK(int[] arr, int k)
    {
      int n = arr.Length;
      int l = 0, u = n - 1, mid;
        
      while(l <= u)
      {
        mid = (l + u)/2;
          
        int numbers_less_than_mid = arr[mid] -
                                        (mid + 1);
          
        // If the total missing number
        // count is equal to k we can iterate
        // backwards for the first missing number
        // and that will be the answer.
        if(numbers_less_than_mid == k)
        {
            
          // To further optimize we check
          // if the previous element's
          // missing number count is equal
          // to k. Eg: arr = [4,5,6,7,8]
          // If you observe in the example array,
          // the total count of missing numbers for all
          // the indices are same, and we are
          // aiming to narrow down the
          // search window and achieve O(logn)
          // time complexity which
          // otherwise would've been O(n).
          if(mid > 0 && (arr[mid - 1] - (mid)) == k)
          {
            u = mid - 1;
            continue;
          }
           
          // Else we return arr[mid] - 1.
          return arr[mid] - 1;
        }
          
        // Here we appropriately
        // narrow down the search window.
        if(numbers_less_than_mid < k)
        {
          l = mid + 1;
        }
        else if(k < numbers_less_than_mid)
        {
          u = mid - 1;
        }
      }
        
      // In case the upper limit is -ve
      // it means the missing number set
      // is 1,2,..,k and hence we directly return k.
      if(u < 0)
        return k;
        
      // Else we find the residual count
      // of numbers which we'd then add to
      // arr[u] and get the missing kth number.
      int less = arr[u] - (u + 1);
      k -= less;
        
      // Return arr[u] + k
      return arr[u] + k;
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = {2,3,4,7,11};
    int k = 5;
    
    // Function Call
    Console.WriteLine("Missing kth number = "+ missingK(arr, k));
  }
}
 
// This code is contributed by divyeshrabadiya07.
输出
Missing kth number = 9

时间复杂度: O(logn),其中n是数组中元素的数量。