You are given an array colors, in which there are three colors: 1, 2 and
3.
You are also given some queries. Each query consists of two integers i and
c, return the shortest distance between the given index i and the target color c. If there is no solution return -1.
Input: colors =[1,1,2,1,3,2,2,3,3], queries =[[1,3],[2,2],[6,1]]Output: [3,0,3]Explanation:
The nearest 3 from index 1is at index 4(3 steps away).The nearest 2 from index 2is at index 2itself(0 steps away).The nearest 1 from index 6is at index 3(3 steps away).
Example 2:
1
2
3
Input: colors =[1,2], queries =[[0,3]]Output: [-1]Explanation: There is no 3in the array.
For each color, precompute the nearest occurrence to the left and right for every index. Then, for each query, the answer is the minimum distance to the nearest occurrence of the target color.
import java.util.*;
classSolution {
public List<Integer>shortestDistanceColor(int[] colors, int[][] queries) {
int n = colors.length;
int[][] left =newint[4][n], right =newint[4][n];
for (int c = 1; c <= 3; ++c) {
int last =-1;
for (int i = 0; i < n; ++i) {
if (colors[i]== c) last = i;
left[c][i]= last;
}
last =-1;
for (int i = n-1; i >= 0; --i) {
if (colors[i]== c) last = i;
right[c][i]= last;
}
}
List<Integer> res =new ArrayList<>();
for (int[] q : queries) {
int i = q[0], c = q[1];
int ans = Integer.MAX_VALUE;
if (left[c][i]!=-1) ans = Math.min(ans, Math.abs(i - left[c][i]));
if (right[c][i]!=-1) ans = Math.min(ans, Math.abs(i - right[c][i]));
res.add(ans == Integer.MAX_VALUE?-1 : ans);
}
return res;
}
}
classSolution:
defshortestDistanceColor(self, colors: list[int], queries: list[list[int]]) -> list[int]:
n = len(colors)
left = [[-1]*n for _ in range(4)]
right = [[-1]*n for _ in range(4)]
for c in range(1,4):
last =-1for i in range(n):
if colors[i]==c: last = i
left[c][i] = last
last =-1for i in range(n-1,-1,-1):
if colors[i]==c: last = i
right[c][i] = last
res = []
for i,c in queries:
ans = float('inf')
if left[c][i]!=-1: ans = min(ans, abs(i-left[c][i]))
if right[c][i]!=-1: ans = min(ans, abs(i-right[c][i]))
res.append(-1if ans==float('inf') else ans)
return res