Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.
You need to help them find out theircommon interestwith theleast list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.
Example 1:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: The only restaurant they both like is "Shogun".
Example 2:
Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
Note:
The length of both lists will be in the range of [1, 1000].
The length of strings in both lists will be in the range of [1, 30].
The index is starting from 0 to the list length minus 1.
最后这题还有一个比较有用的想法是不用hashmap。因为list1跟list2所组成的sum是有限的,我们可以把所有的sum枚举出来。然后我们从list1[0]&list2[sum[0] - i]开始找。如果发现相等的话,我们加到答案里。这里因为sum是一直递增的,所以我们一旦找到某个sum有结果的话,那个结果必定是最小的。所以可以break掉直接返回了。T: O((l1 + l2) ^2 * x), nested loop upto l1 + l2 & string comparison takes x, x is average length of the strings. S: O(r * x), r is len of result
publicString[] findRestaurant(String[] list1,String[] list2) {List < String > res =newArrayList < > ();for (int sum =0; sum <list1.length+list2.length-1; sum++) {for (int i =0; i <= sum; i++) {if (i <list1.length&& sum - i <list2.length&& list1[i].equals(list2[sum - i]))res.add(list1[i]); }if (res.size() >0)break; }returnres.toArray(newString[res.size()]);}