...

/

Solution Review: Find First Unique Integer in an Array

Solution Review: Find First Unique Integer in an Array

This review provides a detailed analysis to solve the "First Unique Integer in an Array" challenge using hashing.

We'll cover the following...

Solution #

Press + to interact
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace chapter_9
{
class challenge_7
{
static int findFirstUnique(int[] arr, int size)
{
Dictionary<int, int> MP = new Dictionary<int, int>(); // createing hash map
for (int i = 0; i < size; i++)
{
if (MP.ContainsKey(arr[i]))
{
MP[arr[i]]++; // inserting elements in hash map
}
else
{
MP[arr[i]] = 1;
}
}
for (int i = 0; i < size; i++)
if (MP[arr[i]] == 1) // if value is equal to 1
return arr[i]; // return that element
return -1;
}
static void Main(string[] args)
{
int[] arr = { -2, 5, -7, 6, 5, -2 };
Console.Write("Array: ");
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
Console.WriteLine("");
int unique = findFirstUnique(arr, arr.Length);
Console.WriteLine("First Unique in an Array: " + unique);
}
}
}

Explanation

Firstly, store all the elements from the array into a dictionary MP (line 13). The element is stored as key, and the ...