My code returns the correct answer the first duplicate is 3 (represented as int f) . I am struggling finding a more efficient way to find the first duplicate?
my constraints are 1 ≤ a.length ≤ 10^5, 1 ≤ a[i] ≤ a.length. Thanks.
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 2, 3, 4, 5, 6 };
int f = FirstDuplicate(a);
Console.ReadLine();
}
public static int FirstDuplicate(int[] a)
{
int[] answer = new int[2];
answer[0] = -1;
answer[1] = a.Length;
for (int i = 0; i < a.Length - 1; i++)
for (int j = i; j < a.Length; j++)
if (a[i] == a[j] && i != j)
{
if (i < answer[1])
{
answer[0] = a[i];
answer[1] = j;
break;
}
}
return answer[0];
}
}