📌  相关文章
📜  排序数组中缺失数字的计数

📅  最后修改于: 2021-05-17 01:53:21             🧑  作者: Mango

给定一个已排序的数组arr [],任务是计算已排序数组的第一个元素和最后一个元素之间缺少的数字数量。

例子:

天真的方法:
解决问题的最简单方法是遍历数组并计算数组元素所有相邻差的总和。

时间复杂度: O(N)
辅助空间: O(1)

高效方法:
为了优化上述方法,我们的想法是观察在[arr [0],arr [N – 1]]范围内的总数为arr [N-1] – arr [0] + 1 。由于数组的大小为N ,因此数组中缺失整数的计数由arr [N-1] – arr [0] + 1 – N给出

下面是上述方法的实现:

C++
// C++ Program for the above approach 
#include  
using namespace std; 
  
// Function that find the count of 
// missing numbers in array a[] 
void countMissingNum(int a[], int N) 
{ 
    // Calculate the count of missing 
    // numbers in the array 
    int count = a[N - 1] - a[0] + 1 - N; 
  
    cout << count << endl; 
} 
  
// Driver Code 
int main() 
{ 
    int arr[] = { 5, 10, 20, 40 }; 
  
    int N = sizeof(arr) / sizeof(arr[0]); 
  
    countMissingNum(arr, N); 
  
    return 0; 
}


Java
// Java program for the above approach 
class GFG{ 
      
// Function that find the count of 
// missing numbers in array a[] 
public static void countMissingNum(int[] a, 
                                int N) 
{ 
      
    // Calculate the count of missing 
    // numbers in the array 
    int count = a[N - 1] - a[0] + 1 - N; 
  
    System.out.println(count); 
} 
  
// Driver code 
public static void main(String[] args) 
{ 
    int arr[] = { 5, 10, 20, 40 }; 
  
    int N = arr.length; 
  
    countMissingNum(arr, N); 
} 
} 
  
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program for the above approach
  
# Function that find the count of 
# missing numbers in array a[] 
def countMissingNum(a, N): 
      
    # Calculate the count of missing 
    # numbers in the array 
    count = a[N - 1] - a[0] + 1 - N 
  
    print(count) 
  
# Driver Code 
arr = [ 5, 10, 20, 40 ] 
  
N = len(arr) 
  
countMissingNum(arr, N) 
  
# This code is contributed by sanjoy_62


C#
// C# program for the above approach 
using System;
  
class GFG{
      
// Function that find the count of 
// missing numbers in array a[] 
public static void countMissingNum(int[] a,
                                   int N) 
{ 
      
    // Calculate the count of missing 
    // numbers in the array 
    int count = a[N - 1] - a[0] + 1 - N; 
  
    Console.Write(count); 
} 
  
// Driver code
public static void Main(string[] args)
{
    int []arr = { 5, 10, 20, 40 }; 
    int N = arr.Length; 
  
    countMissingNum(arr, N); 
}
}
  
// This code is contributed by rutvik_56


输出:
32

时间复杂度: O(1)
辅助空间: O(1)