Shortest Word Distance II
Design, Hash Map
Medium
Design a class which receives a list of words in the constructor, and implements a method that takes two words _word1 _and _word2 _and return the shortest distance between these two words in the list. Your method will be called _repeatedly _many times with different parameters.
Example:
Assume that words =["practice", "makes", "perfect", "coding", "makes"].
Input:
word1
=
“coding”
,
word2
=
“practice”
Output:
3Input:
word1
=
"makes"
,
word2
=
"coding"
Output:
1Note: You may assume thatword1 does not equal to word2, and _word1 _and _word2 _are both in the list.
Analysis
顺序遍历words[],把对应index放入hashmap中<String, ArrayList<Integer>>;这样每个word对应的index其实是默认按照升序排好序了。
shortest()在计算时,brute-force就是两重循环找min。但是更聪明的办法是用two pointers,分别在两个sorted list中,最小的绝对值之差就可以通过一重循环找到了。
Solution
Location mapping, and brute force two nested for loops
shortest() takes
O(pq)time
Optimized - using two pointers
shortest() takes
O(p + q)time
Reference
https://leetcode.com/problems/shortest-word-distance-ii/solution/
Last updated
Was this helpful?