|
34 | 34 | No duplicates in both lists. |
35 | 35 | */ |
36 | 36 | public class _599 { |
37 | | - public String[] findRestaurant(String[] list1, String[] list2) { |
38 | | - if (list1 == null || list2 == null) { |
39 | | - return new String[0]; |
40 | | - } |
41 | | - Map<String, Integer> map1 = putIntoMap(list1); |
42 | | - Map<String, Integer> map2 = putIntoMap(list2); |
43 | | - int leastIndexSum = Integer.MAX_VALUE; |
44 | | - List<String> resultList = new ArrayList<>(); |
45 | | - for (String key1 : map1.keySet()) { |
46 | | - if (map2.containsKey(key1)) { |
47 | | - int indexSum = map1.get(key1) + map2.get(key1); |
48 | | - if (indexSum < leastIndexSum) { |
49 | | - resultList.clear(); |
50 | | - resultList.add(key1); |
51 | | - leastIndexSum = indexSum; |
52 | | - } else if (indexSum == leastIndexSum) { |
53 | | - resultList.add(key1); |
| 37 | + public static class Solution1 { |
| 38 | + public String[] findRestaurant(String[] list1, String[] list2) { |
| 39 | + if (list1 == null || list2 == null) { |
| 40 | + return new String[0]; |
| 41 | + } |
| 42 | + Map<String, Integer> map1 = putIntoMap(list1); |
| 43 | + Map<String, Integer> map2 = putIntoMap(list2); |
| 44 | + int leastIndexSum = Integer.MAX_VALUE; |
| 45 | + List<String> resultList = new ArrayList<>(); |
| 46 | + for (String key1 : map1.keySet()) { |
| 47 | + if (map2.containsKey(key1)) { |
| 48 | + int indexSum = map1.get(key1) + map2.get(key1); |
| 49 | + if (indexSum < leastIndexSum) { |
| 50 | + resultList.clear(); |
| 51 | + resultList.add(key1); |
| 52 | + leastIndexSum = indexSum; |
| 53 | + } else if (indexSum == leastIndexSum) { |
| 54 | + resultList.add(key1); |
| 55 | + } |
54 | 56 | } |
55 | 57 | } |
| 58 | + String[] result = new String[resultList.size()]; |
| 59 | + for (int i = 0; i < resultList.size(); i++) { |
| 60 | + result[i] = resultList.get(i); |
| 61 | + } |
| 62 | + return result; |
56 | 63 | } |
57 | | - String[] result = new String[resultList.size()]; |
58 | | - for (int i = 0; i < resultList.size(); i++) { |
59 | | - result[i] = resultList.get(i); |
60 | | - } |
61 | | - return result; |
62 | | - } |
63 | 64 |
|
64 | | - private Map<String, Integer> putIntoMap(String[] list) { |
65 | | - Map<String, Integer> map = new HashMap<>(); |
66 | | - for (int i = 0; i < list.length; i++) { |
67 | | - map.put(list[i], i); |
| 65 | + private Map<String, Integer> putIntoMap(String[] list) { |
| 66 | + Map<String, Integer> map = new HashMap<>(); |
| 67 | + for (int i = 0; i < list.length; i++) { |
| 68 | + map.put(list[i], i); |
| 69 | + } |
| 70 | + return map; |
68 | 71 | } |
69 | | - return map; |
70 | 72 | } |
71 | 73 | } |
0 commit comments