The minimum sum index leetcode 599 questions. Two lists, sincerely seeking optimization

Suppose Andy and Doris want to choose a restaurant for dinner, and they have expressed a favorite restaurant list, the name of each restaurant is represented by a string.

You need to help them with the least index and find their common favorite restaurant. If the answer is more than one output all the answers and do not consider the order. You can assume that there is always an answer.

Example 1:

Enter:
[ "Shogun", "Tapioca Express", "Burger King", "KFC"]
[ "Piatti", "at The Grill AT Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: [ "Shogun" ]
explanation: their only common favorite restaurant is "Shogun".
Example 2:

Enter:
[ "Shogun", "Tapioca Express", "Burger King", "KFC"]
[ "KFC", "Shogun", "Burger King"]
Output: [ "Shogun"]
to explain: they co-favorite with minimal index and restaurant are "Shogun", which has the smallest index and 1 (0 + 1).


prompt:

Length two lists are [1, 1000] within.

Length of the string within the two lists will be in the range [1,30] of.

Index from 0 to 1 minus the length of the list.

Both lists are no duplicate elements.

 

 

    public string[] FindRestaurant(string[] list1, string[] list2) {
           Dictionary<string, int> dic = new Dictionary<string, int>(list1.Length);
            for (int i = 0; i < list1.Length; i++)
            {
                dic.Add(list1[i], i);
            }
            List<string> result = new List<string>();
            int min = -1;
            for (int i = 0; i < list2.Length; i++)
            { 
                if (dic.Keys.Contains(list2[i]))
                {
                    int t = i + dic[list2[i]];
                    if (min == -1 || min == t)
                    {
                        min = t;
                        result.Add(list2[i]);
                    }
                    else if (t < min)
                    {
                        min = t;
                        result.Clear();
                        result.Add(list2[i]);
                    }
                }
            }
           return result.ToArray();
    }

 

Effect is very bad:

When execution: 504 ms, beat the 79.31% of all users to submit in C #
Memory consumption: 39.9 MB, defeated 75.00% of all users to submit in C #
 
Sincerely seek to optimize

 

Guess you like

Origin www.cnblogs.com/refuge/p/11031765.html