File tree 1 file changed +38
-0
lines changed
1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public String [] findRestaurant (String [] list1 , String [] list2 ) {
3
+ Map <String , Integer > map1 = createMap (list1 );
4
+ Map <String , Integer > map2 = createMap (list2 );
5
+ int minIndexSum = Integer .MAX_VALUE ;
6
+ int count = 0 ;
7
+ for (String key : map1 .keySet ()) {
8
+ if (map2 .containsKey (key )) {
9
+ int idxSum = map1 .get (key ) + map2 .get (key );
10
+ if (idxSum < minIndexSum ) {
11
+ minIndexSum = idxSum ;
12
+ count = 1 ;
13
+ }
14
+ else if (idxSum == minIndexSum ){
15
+ count ++;
16
+ }
17
+ }
18
+ }
19
+ String [] ans = new String [count ];
20
+ int idx = 0 ;
21
+ for (String key : map1 .keySet ()) {
22
+ if (map2 .containsKey (key )) {
23
+ if (map1 .get (key ) + map2 .get (key ) == minIndexSum ) {
24
+ ans [idx ++] = key ;
25
+ }
26
+ }
27
+ }
28
+ return ans ;
29
+ }
30
+
31
+ private Map <String , Integer > createMap (String [] list ) {
32
+ Map <String , Integer > map = new HashMap <>();
33
+ for (int i = 0 ; i < list .length ; i ++) {
34
+ map .put (list [i ], i );
35
+ }
36
+ return map ;
37
+ }
38
+ }
You can’t perform that action at this time.
0 commit comments