Find the non-repeating number in C++

Non-Repeating Element

c++


Find the first non-repeating element in a given array of integers.

Examples:

Input : -4 2 -4 3 2
Output : 3
Explanation : The first number that does not 
repeat is : 3

Input : 8 3 8 6 7 3
Output : 6

Code:

//Simple CPP program to find first non- repeating element.

#include <bits/stdc++.h>
using namespace std;

int nonRepeating(int arr[], int n)
{
for (int i = 0; i < n; i++) {
int j;
for (j = 0; j < n; j++)
if (i != j && arr[i] == arr[j])
break;
if (j == n)
return arr[i];
}
return -1;
}

int main()
{
int arr[] = { 8,3,8,6,7,3 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << nonRepeating(arr, n);
return 0;
}


Output:
6
Share:
spacer

No comments:

Post a Comment