Computer Science, asked by aman2068, 9 months ago

In 'sorting' once the value of the first element has been compared with all the other elements in the array it is said to have completed a/an _________________ . Order other objective not stated above. Pass phase session

Answers

Answered by Anonymous
0

Answer:

Given an array arr that has numbers appearing twice or once. The task is to identify numbers that occurred only once in the array.

Note: Duplicates appear side by side every time. Might be few numbers can occur one time and just assume this is a right rotating array (just say an array can rotate k times towards right). Order of the elements in the output doesn’t matter.

Examples:

Input: arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 }

Output: 9 4

Input: arr[] = {-9, -8, 4, 4, 5, 5, -1}

Output: -9 -8 -1

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Method-1: Using Sorting.

Sort the array.

Check for each element at index i (except the first and last element), if

arr[i] != arr[i-1] && arr [i] != arr[i+1]

For the first element, check if arr[0] != arr[1].

For the last element, check if arr[n-1] != arr[n-2].

Below is the implementation of above approach:

C++

// C++ implementation of above approach

#include <bits/stdc++.h>

using namespace std;

// Function to find the elements that

// appeared only once in the array

void occurredOnce(int arr[], int n)

{

// Sort the array

sort(arr, arr + n);

// Check for first element

if (arr[0] != arr[1])

cout << arr[0] << " ";

// Check for all the elements if it is different

// its adjacent elements

for (int i = 1; i < n - 1; i++)

if (arr[i] != arr[i + 1] && arr[i] != arr[i - 1])

cout << arr[i] << " ";

// Check for the last element

if (arr[n - 2] != arr[n - 1])

cout << arr[n - 1] << " ";

}

// Driver code

int main()

{

int arr[] = { 7, 7, 8, 8, 9, 1, 1, 4, 2, 2 };

int n = sizeof(arr) / sizeof(arr[0]);

occurredOnce(arr, n);

return 0;

#followme

#markasbrainlist

....

Similar questions