LeetCode 599. Minimum Index Sum of Two Lists (从两个lists里找到相同的并且位置总和最靠前的)
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 their common interest with the least 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.
- No duplicates in both lists.
题目标签:Hash Table
这道题让我们从两个list中找出相同的string并且它们的index sum是最小的,意思就是让我们找到他们两个都想吃的同一个饭店,并且这个饭店是他们排位里最靠前的。
Step 1: 首先我们建立一个HashMap, 遍历list1, 把饭店string作为key, 把index作为value保存进map。
Step 2: 建立一个HashSet, 遍历list2, 如果找到list2里的饭店string是在之前的map里的话,更新一下map的value = index1(之前的value) + index2(在list2里的);并且设一个min,在记录最小的index sum,把最小的饭店string保存进set里面。
当找到一个相同的index sum = min的话,把这个饭店string加入set;当找到更小的min的时候,要把set清空,因为出现更小的index sum的饭店了,淘汰前面的饭店,重设min的值。
Step 3: 此时set里的饭店名就是最靠前的并且是两个list都有的,设置一个string array把答案copy进去return。
Java Solution:
Runtime beats 69.17%
完成日期:06/07/2017
1 public class Solution 2 { 3 public String[] findRestaurant(String[] list1, String[] list2) 4 { 5 HashMap<String, Integer> map = new HashMap<>(); 6 7 // put list1's string as key, index as value. 8 for(int i=0; i<list1.length; i++) 9 map.put(list1[i], i); 10 11 12 13 HashSet<String> set = new HashSet<>(); 14 15 int min = Integer.MAX_VALUE; 16 17 // iterate list2 to see any string is in map 18 for(int i=0; i<list2.length; i++) 19 { 20 if(map.get(list2[i]) != null) // if list2's string is in map 21 { 22 int j = map.get(list2[i]); 23 map.put(list2[i], i + j); // update map's value 24 25 if(i+j == min) // if find another same min value, add this string to set. 26 set.add(list2[i]); 27 else if(i+j < min) // if find another smaller index 28 { 29 set.clear(); // clear the set. 30 set.add(list2[i]); // add smaller index string into set. 31 min = i+j; // update the min; 32 } 33 34 35 } 36 } 37 38 String[] res = new String[set.size()]; 39 40 int i=0; 41 for(String s : set) 42 { 43 res[i] = s; 44 i++; 45 } 46 47 48 return res; 49 } 50 }
参考资料:
http://blog.csdn.net/kangbin825/article/details/72794253
LeetCode 算法题目列表 - LeetCode Algorithms Questions List