📜  门| GATE-CS-2015(Set 1)|第65章(1)

📅  最后修改于: 2023-12-03 15:12:42.481000             🧑  作者: Mango

GATE-CS-2015(Set 1) - Question 65

Introduction

In this question, we are given a partially implemented C++ function that is supposed to remove all duplicates from an array. The task is to complete the function implementation.

Function Signature

The function signature is as follows:

int* removeDuplicates(int arr[], int n);

It takes an integer array arr of size n as input and returns a pointer to an integer array.

Function Implementation

The partially implemented function is:

int* removeDuplicates(int arr[], int n)
{
    // To do: Complete implementation
}

The task is to complete the implementation of this function so that it removes all duplicates from the input array and returns a pointer to a new array containing only distinct elements.

Approach

We can use a hash table to keep track of the elements that have already occurred in the array. We traverse the input array and for each element, we check whether it is already present in the hash table. If it is not, we add it to the hash table and also to a new array. If it is already present, we skip it.

After we have traversed the entire input array, we return the new array containing distinct elements.

Final Function

The final implementation of the function is:

int* removeDuplicates(int arr[], int n)
{
    unordered_set<int> hash;
    int* new_arr = new int[n];
    int count = 0;

    for (int i = 0; i < n; i++) {
        if (hash.find(arr[i]) == hash.end()) {
            hash.insert(arr[i]);
            new_arr[count++] = arr[i];
        }
    }

    return new_arr;
}
Time and Space Complexity

The time complexity of this function is O(n) because we traverse the entire input array exactly once.

The space complexity of this function is O(n) because we create a new array of size n to store distinct elements. We also create a hash table of size n at most.