-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
49 lines (48 loc) · 1.56 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using System;
using System.Collections.Generic;
namespace ShortestDistanceToTargetColor
{
class Program
{
static void Main(string[] args)
{
int[] colors = { 1, 1, 2, 1, 3, 2, 2, 3, 3 };
int[][] queries = new int[][]
{
new int[]{1, 3},
new int[]{2, 2},
new int[]{6, 1},
};
Console.WriteLine(ShortestDistanceColor(colors, queries));
}
static IList<int> ShortestDistanceColor(int[] colors, int[][] queries)
{
var res = new List<int>();
var dict = new Dictionary<int, List<int>>();
for (int i = 0; i < colors.Length; i++)
{
if (!dict.ContainsKey(colors[i]))
dict[colors[i]] = new List<int>();
dict[colors[i]].Add(i);
}
foreach (var query in queries)
{
if (!dict.ContainsKey(query[1]))
{
res.Add(-1);
continue;
}
var indeics = dict[query[1]];
var pos = indeics.BinarySearch(query[0]);
pos = pos < 0 ? -(pos + 1) : pos;
if (pos == 0)
res.Add(indeics[0] - query[0]);
else if (pos == indeics.Count)
res.Add(query[0] - indeics[^1]);
else
res.Add(Math.Min(query[0] - indeics[pos - 1], indeics[pos] - query[0]));
}
return res;
}
}
}