给定大小为n的数组。还给出数字范围是从smallestNumber到smallestNumber + n,其中minimumNumber是数组中的最小数字。数组包含此范围内的数字,但缺少一个数字,因此任务是找到此缺失的数字。
例子:
Input : arr[] = {13, 12, 11, 15}
Output : 14
Input : arr[] = {33, 36, 35, 34};
Output : 37
问题非常接近,找不到丢失的号码。
有很多方法可以解决此问题。
一种简单的方法是先找到最小值,然后一个个地搜索所有元素。该方法的时间复杂度为O(n * n)
更好的解决方案是对数组进行排序。然后遍历数组,找到不存在的第一个元素。这种方法的时间复杂度是O(n Log n)
最好的解决方案是先对所有数字进行异或。然后,将此结果与从最小数到n + smallestNumber的所有数字进行异或。 XOR是我们的结果。
例子:-
arr[n] = {13, 12, 11, 15}
smallestNumber = 11
first find the xor of this array
13^12^11^15 = 5
Then find the XOR first number to first number + n
11^12^13^14^15 = 11;
Then xor these two number's
5^11 = 14 // this is the missing number
C++
// CPP program to find missing
// number in a range.
#include
using namespace std;
// Find the missing number
// in a range
int missingNum(int arr[], int n)
{
int minvalue = *min_element(arr, arr+n);
// here we xor of all the number
int xornum = 0;
for (int i = 0; i < n; i++) {
xornum ^= (minvalue) ^ arr[i];
minvalue++;
}
// xor last number
return xornum ^ minvalue;
}
// Driver code
int main()
{
int arr[] = { 13, 12, 11, 15 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << missingNum(arr, n);
return 0;
}
Java
// Java program to find
// missing number in a range.
import java.io.*;
import java.util.*;
class GFG {
// Find the missing number in a range
static int missingNum(int arr[], int n)
{
List list = new ArrayList<>(arr.length);
for (int i :arr)
{
list.add(Integer.valueOf(i));
}
int minvalue = Collections.min(list);;
// here we xor of all the number
int xornum = 0;
for (int i = 0; i < n; i++) {
xornum ^= (minvalue) ^ arr[i];
minvalue++;
}
// xor last number
return xornum ^ minvalue;
}
public static void main (String[] args) {
int arr[] = { 13, 12, 11, 15 };
int n = arr.length;
System.out.println(missingNum(arr, n));
}
}
//This code is contributed by Gitanjali.
Python3
# python3 program to check
# missingnumber in a range
# Find the missing number
# in a range
def missingNum( arr, n):
minvalue = min(arr)
# here we xor of all the number
xornum = 0
for i in range (0,n):
xornum ^= (minvalue) ^ arr[i]
minvalue = minvalue+1
# xor last number
return xornum ^ minvalue
# Driver method
arr = [ 13, 12, 11, 15 ]
n = len(arr)
print (missingNum(arr, n))
# This code is contributed by Gitanjali.
C#
// C# program to find
// missing number in a range.
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
// Find the missing number in a range
static int missingNum(int []arr, int n)
{
List list = new List(arr.Length);
foreach (int i in arr)
{
list.Add(i);
}
int minvalue = list.Min();
// here we xor of all the number
int xornum = 0;
for (int i = 0; i < n; i++)
{
xornum ^= (minvalue) ^ arr[i];
minvalue++;
}
// xor last number
return xornum ^ minvalue;
}
// Driver Code
public static void Main (String[] args)
{
int []arr = { 13, 12, 11, 15 };
int n = arr.Length;
Console.WriteLine(missingNum(arr, n));
}
}
// This code is contributed by Rajput-Ji
PHP
输出:
14