Given a 1D integer array of size n. Range of elements is natural numbers from 1 to n. One number is missing, and one occurs twice. Your task is to find these two numbers.
For example: Arr[9] : 5 6 4 3 2 1 3 7 9 Missing element: 8
Element that occurs twice: 3
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
cout << "Please, enter a size of array: ";
cin >> n;
int* arr = new int[n];
cout << "Please, enter " << n << " values: ";
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
sort(&arr[0], &arr[n]);
int miss = 0;
int twice = 0;
for (int i = 0; i < n; i++)
{
if (i > 0)
{
if (arr[i] - arr[i - 1] != 1)
{
if (arr[i] == arr[i - 1])
{
twice = i;
}
else if (arr[i] - arr[i - 1] == 2)
{
miss = arr[i] - 1;
}
}
}
}
cout << "\nMissing element: " << miss;
cout << "\nElement that occurs twice: " << arr[twice];
}
Comments
Leave a comment