classSolution: deffindRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: index = {s: i for i, s inenumerate(list1)} ans = [] indexSum = inf for i, s inenumerate(list2): if s in index: j = index[s] if i + j < indexSum: indexSum = i + j ans = [s] elif i + j == indexSum: ans.append(s) return ans
publicclassSolution { publicstring[] FindRestaurant(string[] list1, string[] list2) { Dictionary<string, int> index = new Dictionary<string, int>(); for (int i = 0; i < list1.Length; i++) { index.Add(list1[i], i); }
IList<string> ret = new List<string>(); int indexSum = int.MaxValue; for (int i = 0; i < list2.Length; i++) { if (index.ContainsKey(list2[i])) { int j = index[list2[i]]; if (i + j < indexSum) { ret.Clear(); ret.Add(list2[i]); indexSum = i + j; } elseif (i + j == indexSum) { ret.Add(list2[i]); } } } return ret.ToArray(); } }
var findRestaurant = function(list1, list2) { const index = newMap(); for (let i = 0; i < list1.length; i++) { index.set(list1[i], i); }
const ret = []; let indexSum = Number.MAX_VALUE; for (let i = 0; i < list2.length; i++) { if (index.has(list2[i])) { const j = index.get(list2[i]); if (i + j < indexSum) { ret.length = 0; ret.push(list2[i]); indexSum = i + j; } elseif (i + j == indexSum) { ret.push(list2[i]); } } } return ret; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcfindRestaurant(list1, list2 []string) (ans []string) { index := make(map[string]int, len(list1)) for i, s := range list1 { index[s] = i }
indexSum := math.MaxInt32 for i, s := range list2 { if j, ok := index[s]; ok { if i+j < indexSum { indexSum = i + j ans = []string{s} } elseif i+j == indexSum { ans = append(ans, s) } } } return }