📜  在有限范围的排序数组中查找缺失的数字

📅  最后修改于: 2022-05-13 01:57:47.888000             🧑  作者: Mango

在有限范围的排序数组中查找缺失的数字

给定一个大小为 n 的排序数组,并假设有从 1 到 n+1 的数字,其中一个缺失,要找到缺失的数字。可以假设数组具有不同的元素。
例子:

Input : 1 3 4 5 6
Output : 2

Input  : 1 2 3 4 5 7 8 9 10
Output  : 6

我们遍历所有元素。对于每个元素 a[i],我们检查它是否等于 i+1。如果不是,我们返回 (i+1)。

C++
// C++ program to find missing Number in
// a sorted array of size n and distinct
// elements.
#include
using namespace std;
 
// Function to find missing number
int getMissingNo(int a[], int n)
{
    for (int i=0; i


Java
// Java program to find missing Number in
// a sorted array of size n and distinct
// elements.
class Main
{
    // Function to find missing number
    static int getMissingNo(int a[])
    {
        int n = a.length;
        for (int i=0; i


Python3
# Python program to find missing Number in
# a sorted array of size n and distinct
# elements.
 
# function to find missing number
def getMissingNo(a):
    n = len(a)
     
    for i in range(n):
        if(a[i] != i + 1):
            return i + 1
             
    # If all numbers from 1 to n
    # are present
    return n+1
 
# Driver code
a = [1, 2, 4, 5, 6]
print(getMissingNo(a))
 
# This code is contributed by Sachin Bisht


C#
// C# program to find missing Number
// in a sorted array of size n and
// distinct elements.
using System;
 
class GFG
{
     
// Function to find missing number
static int getMissingNo(int []a, int n)
{
    for (int i = 0; i < n; i++)
        if (a[i] != (i + 1))
            return (i + 1);
 
    // If all numbers from
    // 1 to n are present
    return n + 1;
}
 
// Driver code
public static void Main()
{
    int []a = {1, 2, 4, 5, 6};
    int n = a.Length;
    Console.WriteLine(getMissingNo(a, n));
}
}
 
// This code is contributed by ihritik


PHP


Javascript


输出 :

3

时间复杂度: O(n)