|
34 | 34 | No duplicates in both lists.
|
35 | 35 | */
|
36 | 36 | publicclass_599 {
|
37 |
| -publicString[]findRestaurant(String[]list1,String[]list2) { |
38 |
| -if (list1 ==null ||list2 ==null) { |
39 |
| -returnnewString[0]; |
40 |
| - } |
41 |
| -Map<String,Integer>map1 =putIntoMap(list1); |
42 |
| -Map<String,Integer>map2 =putIntoMap(list2); |
43 |
| -intleastIndexSum =Integer.MAX_VALUE; |
44 |
| -List<String>resultList =newArrayList<>(); |
45 |
| -for (Stringkey1 :map1.keySet()) { |
46 |
| -if (map2.containsKey(key1)) { |
47 |
| -intindexSum =map1.get(key1) +map2.get(key1); |
48 |
| -if (indexSum <leastIndexSum) { |
49 |
| -resultList.clear(); |
50 |
| -resultList.add(key1); |
51 |
| -leastIndexSum =indexSum; |
52 |
| - }elseif (indexSum ==leastIndexSum) { |
53 |
| -resultList.add(key1); |
| 37 | +publicstaticclassSolution1 { |
| 38 | +publicString[]findRestaurant(String[]list1,String[]list2) { |
| 39 | +if (list1 ==null ||list2 ==null) { |
| 40 | +returnnewString[0]; |
| 41 | + } |
| 42 | +Map<String,Integer>map1 =putIntoMap(list1); |
| 43 | +Map<String,Integer>map2 =putIntoMap(list2); |
| 44 | +intleastIndexSum =Integer.MAX_VALUE; |
| 45 | +List<String>resultList =newArrayList<>(); |
| 46 | +for (Stringkey1 :map1.keySet()) { |
| 47 | +if (map2.containsKey(key1)) { |
| 48 | +intindexSum =map1.get(key1) +map2.get(key1); |
| 49 | +if (indexSum <leastIndexSum) { |
| 50 | +resultList.clear(); |
| 51 | +resultList.add(key1); |
| 52 | +leastIndexSum =indexSum; |
| 53 | + }elseif (indexSum ==leastIndexSum) { |
| 54 | +resultList.add(key1); |
| 55 | + } |
54 | 56 | }
|
55 | 57 | }
|
| 58 | +String[]result =newString[resultList.size()]; |
| 59 | +for (inti =0;i <resultList.size();i++) { |
| 60 | +result[i] =resultList.get(i); |
| 61 | + } |
| 62 | +returnresult; |
56 | 63 | }
|
57 |
| -String[]result =newString[resultList.size()]; |
58 |
| -for (inti =0;i <resultList.size();i++) { |
59 |
| -result[i] =resultList.get(i); |
60 |
| - } |
61 |
| -returnresult; |
62 |
| - } |
63 | 64 |
|
64 |
| -privateMap<String,Integer>putIntoMap(String[]list) { |
65 |
| -Map<String,Integer>map =newHashMap<>(); |
66 |
| -for (inti =0;i <list.length;i++) { |
67 |
| -map.put(list[i],i); |
| 65 | +privateMap<String,Integer>putIntoMap(String[]list) { |
| 66 | +Map<String,Integer>map =newHashMap<>(); |
| 67 | +for (inti =0;i <list.length;i++) { |
| 68 | +map.put(list[i],i); |
| 69 | + } |
| 70 | +returnmap; |
68 | 71 | }
|
69 |
| -returnmap; |
70 | 72 | }
|
71 | 73 | }
|