|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.HashMap; |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +public class MinimumIndexSumOfTwoLists { |
| 7 | + public String[] findRestaurant(String[] list1, String[] list2) { |
| 8 | + int indexSum = Integer.MAX_VALUE; |
| 9 | + List<String> result = new ArrayList<>(); |
| 10 | + Map<String, Integer> restaurantIndices = getValueToIndexMap(list1); |
| 11 | + for (int index = 0 ; index < list2.length ; index++) { |
| 12 | + if (restaurantIndices.containsKey(list2[index])) { |
| 13 | + if (index + restaurantIndices.get(list2[index]) < indexSum) { |
| 14 | + result.clear(); |
| 15 | + result.add(list2[index]); |
| 16 | + indexSum = index + restaurantIndices.get(list2[index]); |
| 17 | + } else if(index + restaurantIndices.get(list2[index]) == indexSum) { |
| 18 | + result.add(list2[index]); |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + return toArray(result); |
| 23 | + } |
| 24 | + |
| 25 | + private String[] toArray(List<String> strings) { |
| 26 | + String[] result = new String[strings.size()]; |
| 27 | + for (int index = 0 ; index < result.length ; index++) { |
| 28 | + result[index] = strings.get(index); |
| 29 | + } |
| 30 | + return result; |
| 31 | + } |
| 32 | + |
| 33 | + private Map<String, Integer> getValueToIndexMap(String[] array) { |
| 34 | + Map<String, Integer> result = new HashMap<>(); |
| 35 | + for (int index = 0 ; index < array.length ; index++) { |
| 36 | + result.put(array[index], index); |
| 37 | + } |
| 38 | + return result; |
| 39 | + } |
| 40 | +} |
0 commit comments