Answer to Question #345236 in C++ for Uzi

Question #345236

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

1
Expert's answer
2022-05-26T09:35:21-0400
#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];
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS