首页 > 代码库 > 599. 列表下标最小和 Minimum Index Sum of Two Lists

599. 列表下标最小和 Minimum Index Sum of Two Lists

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:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".

Example 2:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["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).

Note:

  1. The length of both lists will be in the range of [1, 1000].
  2. The length of strings in both lists will be in the range of [1, 30].
  3. The index is starting from 0 to the list length minus 1.
  4. No duplicates in both lists.


  1. public class Solution {
  2. public string[] FindRestaurant(string[] list1, string[] list2) {
  3. List<Pair> listPair1 = new List<Pair>();
  4. for(int i = 0;i<list1.Length;i++)
  5. {
  6. Pair pair =new Pair(list1[i], i);
  7. listPair1.Add(pair);
  8. }
  9. List<string> lowestMatchList = new List<string>();
  10. int lowestMatchIndex = Int32.MaxValue;
  11. for(int i = 0;i<list2.Length;i++)
  12. {
  13. foreach(Pair pair in listPair1)
  14. {
  15. string restaurant = list2[i];
  16. if(restaurant== pair.Restaurant)
  17. {
  18. int sum = i + pair.Index;
  19. if(sum == lowestMatchIndex)
  20. {
  21. lowestMatchList.Add(restaurant);
  22. }
  23. else if(sum < lowestMatchIndex)
  24. {
  25. lowestMatchIndex = sum;
  26. if(lowestMatchList.Count > 0)
  27. {
  28. lowestMatchList.Remove(lowestMatchList[0]);
  29. }
  30. lowestMatchList.Add(restaurant);
  31. }
  32. }
  33. }
  34. }
  35. return lowestMatchList.ToArray();
  36. }
  37. public class Pair
  38. {
  39. public string Restaurant {get;set;}
  40. public int Index {get;set;}
  41. public Pair(string restaurant, int index)
  42. {
  43. Restaurant = restaurant;
  44. Index = index;
  45. }
  46. }
  47. }




null


599. 列表下标最小和 Minimum Index Sum of Two Lists