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 their favorite restaurants, each with a string of names.

You need to help them index and find their favorite restaurants with the least amount If there is more than one answer, all the answers are output regardless of the order You can assume that there is always an answer.

Example 1:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: their only favorite restaurant is "Shogun".

Example 2:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: their favorite restaurant with the smallest index sum is "Shogun", which has the smallest index and 1 (0 + 1).

Tips:

  1. The length range of both lists is within [1, 1000].
  2. The length of strings in both lists will be in the range of [1, 30].
  3. The subscript starts at 0, and the length to the list decreases by 1.
  4. Neither list has duplicate elements.
    class Solution {
    public:
        vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
            vector<string> vec;
            if(list1.size()==1)
            {
                vec.push_back(list1[0]);
                return vec;
            }   
            if(list2.size()==1)
            {
                vec.push_back(list2[0]);
                return vec;
            } 
            int index=0;
            int sum=INT_MAX;
            for(int i=0;i<list1.size();i++)
            {
                index=find(list2.begin(),list2.end(),list1[i])-list2.begin();
                if(index!=list2.size())
                {
                    if(vec.size()>0)
                    {
                        if(sum>(i+index))
                        {
                            vec.clear();
                            vec.push_back(list1[i]);
                            sum=i+index;
                        }
                        else if(sum==(i+index))
                        {
                            vec.push_back(list1[i]);
                            sum=i+index;
                        }
    
                    }
                    else if(vec.size()==0)
                    {
                        if(sum>=(i+index))
                        {
                            vec.push_back(list1[i]);
                            sum=i+index;
                        }
                    }
                }
            }
            return vec;
        }
    };

     

Posted by stanleybb on Wed, 13 Nov 2019 10:24:16 -0800