CSharp · Console
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static bool ContainsNearbyDuplicate(int[] nums, int k)
{
var dict = new Dictionary<int, List<int>>();
for (int i = 0; i < nums.Length; i++)
{
int key = nums[i];
if (!dict.ContainsKey(key))
{
dict[key] = new List<int>() { i };
}
else
{
if (dict[key].Any(x => Math.Abs(x - i) <= k))
{
return true;
}
dict[key].Add(i);
}
}
return false;
}
public static void Main()
{
Console.WriteLine("UniLecs");
int[] arr = new int[] { 1, 2, 3, 1 };
Console.WriteLine(ContainsNearbyDuplicate(arr, 3)); // true
arr = new int[] { 1, 0, 1, 1 };
Console.WriteLine(ContainsNearbyDuplicate(arr, 1)); // true
arr = new int[] { 1, 2, 3, 1, 2, 3 };
Console.WriteLine(ContainsNearbyDuplicate(arr, 2)); // false
}
}