leetcode 599. Minimum Index Sum of Two Lists | 599. 两个列表的最小索引总和
生活随笔
收集整理的這篇文章主要介紹了
leetcode 599. Minimum Index Sum of Two Lists | 599. 两个列表的最小索引总和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/
題解
思路和題解一致,用 map 搞定。效率低可能是因為建了兩個 map。
import java.util.ArrayList; import java.util.HashMap; import java.util.Map;class Solution {public String[] findRestaurant(String[] list1, String[] list2) {HashMap<String, Integer> map1 = new HashMap<>();for (int i = 0; i < list1.length; i++)map1.put(list1[i], i);HashMap<String, Integer> map2 = new HashMap<>();for (int i = 0; i < list2.length; i++)if (map1.containsKey(list2[i])) map2.put(list2[i], map1.get(list2[i]) + i);int min = Integer.MAX_VALUE;for (Map.Entry<String, Integer> e : map2.entrySet())min = Math.min(min, e.getValue());ArrayList<String> list = new ArrayList<>();for (Map.Entry<String, Integer> e : map2.entrySet())if (e.getValue() == min) list.add(e.getKey());String[] result = new String[list.size()];list.toArray(result);return result;} }總結
以上是生活随笔為你收集整理的leetcode 599. Minimum Index Sum of Two Lists | 599. 两个列表的最小索引总和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 598. Range
- 下一篇: leetcode 605. Can Pl