題目描述:
Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
Example 1:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
Example 3:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Burger King","Tapioca Express","Shogun"]
Output: ["KFC","Burger King","Tapioca Express","Shogun"]
Example 4:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KNN","KFC","Burger King","Tapioca Express","Shogun"]
Output: ["KFC","Burger King","Tapioca Express","Shogun"]
Example 5:
Input: list1 = ["KFC"], list2 = ["KFC"]
Output: ["KFC"]
Constraints:
1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i]
andlist2[i]
consist of spaces' '
and English letters.All the stings of
list1
are unique.All the stings of
list2
are unique.
一刷題解(Dictionary):
這題需要我們在兩個字符串數組中,找出共同的字符串,並將它們在各自的數組中的下標進行求和,把下標值總和最小的一或多個字符串返回出去。這一題其實是一道非常簡單的Dictonary應用題,整個解題步驟只有簡單的三步:
- 將其中一個數組的元素加到一個記錄字符串和字符串的下標總和的字典裡。
- 遍歷另一個數組,檢查哪些元素與字典裡的字符串相同,並把下標的值加到對應的條目的Value上。
- 檢查當前字符串的下標總和是否小於當前最小下標總和,是的話就清空結果數組並最小下標總和;如果等於最小下標總和就將當前字符串加到結果數組的尾部;如果大於那就直接continue。
public class Solution {
public string[] FindRestaurant(string[] list1, string[] list2) {
if (list1 == null || list2 == null) { return null; }
//字符串-下標總和字典
Dictionary<string, int> commonDict = new Dictionary<string, int>();
List<string> result = new List<string>();
//遍歷其中一個數組,把字符串和下標加到字典裡
for (int i = 0; i < list1.Length; i++)
{
commonDict.Add(list1[i], i);
}
//默認最小的下標總和是最壞的情況(下標總和上限 -> 兩個數組長度的和)
int leastIdx = list1.Length + list2.Length;
//遍歷另一個數組,查找共同字符串
for (int i = 0; i < list2.Length; i++)
{
if (commonDict.ContainsKey(list2[i]))
{
//進行下標的加總和判斷
if(commonDict[list2[i]] + i < leastIdx)
{
leastIdx = commonDict[list2[i]] + i;
result.Clear();
result.Add(list2[i]);
}
else if(commonDict[list2[i]] + i == leastIdx)
{
result.Add(list2[i]);
}
else
{
continue;
}
}
}
return result.ToArray();
}
}