Given two arrays of strings list1
and list2
, find the common strings with the least index sum.
A common string is a string that appeared in both list1
and list2
.
A common string with the least index sum is a common string such that if it appeared at list1[i]
and list2[j]
then i + j
should be the minimum value among all the other common strings.
Return all the common strings with the least index sum. Return the answer in any order.
Example 1:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"] Output: ["Shogun"] Explanation: The only common string is "Shogun".
Example 2:
Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"] Output: ["Shogun"] Explanation: The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1.
Example 3:
Input: list1 = ["happy","sad","good"], list2 = ["sad","happy","good"] Output: ["sad","happy"] Explanation: There are three common strings: "happy" with index sum = (0 + 1) = 1. "sad" with index sum = (1 + 0) = 1. "good" with index sum = (2 + 2) = 4. The strings with the least index sum are "sad" and "happy".
Constraints:
1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30
list1[i]
andlist2[i]
consist of spaces' '
and English letters.- All the strings of
list1
are unique. - All the strings of
list2
are unique.
题目给了两个数组,要找这两个数组里相同元素的index之和最小的元素们。其实就很直观,用一个map把第一个数组遍历一遍存放<string, index>,然后遍历第二个数组看看有没有出现在第一个里面,如果有的话就计算一下index之和,进行比较就行。刚开始给它想复杂了还把第二个数组的index也存到了map里(map是<string, List<index>>),就,大可不必。看了solutions还写了俩句复杂的方法然而都不是最优解就不看了。
Runtime: 8 ms, faster than 97.07% of Java online submissions for Minimum Index Sum of Two Lists.
Memory Usage: 43 MB, less than 86.82% of Java online submissions for Minimum Index Sum of Two Lists.
class Solution {
public String[] findRestaurant(String[] list1, String[] list2) {
Map<String, Integer > map = new HashMap<>();
int min = Integer.MAX_VALUE;
List<String> result = new ArrayList<>();
for (int i = 0; i < list1.length; i++) {
map.put(list1[i], i);
}
for (int i = 0; i < list2.length; i++) {
if (map.containsKey(list2[i])) {
int sum = map.get(list2[i]) + i;
if (sum < min) {
min = sum;
result = new ArrayList<>();
result.add(list2[i]);
} else if (sum == min) {
result.add(list2[i]);
}
}
}
return result.toArray(new String[0]);
}
}