LeetCode 题解之Minimum Index Sum of Two Lists

1、题目描述

2.问题分析

直接是用hash table 解决问题

3、代码

 1 vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
 2        
 3         vector<string> result;
 4         map<string,int>m;
 5         for(int i = 0; i < list1.size() ; i++ )
 6         {
 7             m.insert( std::pair<string,int>( list1[i],i) ) ;
 8         }
 9         
10         map<string,int>m2 ;
11         for(int i = 0; i < list2.size() ; i++ )
12         {
13             m2.insert( std::pair<string,int>(list2[i],i) );
14         }
15         
16         int min_index = list1.size() + list2.size() ;
17         
18         for( map<string,int>::iterator it = m.begin() ; it != m.end() ; it++ )
19         {
20            auto it_find = m2.find( it->first );
21            if( it_find != m2.end() )
22            {
23                int index_sum = it->second + it_find->second;
24                if( index_sum < min_index )
25                {
26                    result.clear();
27                    result.push_back( it->first) ;
28                    min_index = index_sum;
29                }else if( index_sum == min_index )
30                {
31                    result.push_back( it->first ) ;
32                }
33                
34            }
35         }
36 
37         return result;
38         
39     }

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/9290977.html