CS
Algorithm
Algorithm
  • lintcode
  • EPI
    • String
      • Base Convert
  • Graph
    • Inorder Successor in BST
    • Balanced Binary Tree
    • All Paths From Source to Target
  • LinkedIn
    • House robber II
    • Single Number
    • Flatten Binary Tree to Linked List
    • Smallest Difference pair of values between two unsorted Arrays
    • Word Search II
    • Implement Trie (Prefix Tree)
    • K Closest Points
    • implement BST
    • HashMap
    • Implement strStr()
    • Min Stack
    • Meeting Rooms
    • Shortest Completing Word
    • Longest Palindromic Substring
    • Longest Palindromic Subsequence
    • Count Different Palindromic Subsequences
    • Palindromic Substrings
    • Sparse Matrix Multiplication
    • Insert Delete GetRandom O(1) - Duplicates allowed
    • Bulb Switcher
    • Verify Preorder Sequence in Binary Search Tree
    • Untitled
    • Find the Celebrity
    • Coin Change
    • Partition Equal Subset Sum
    • Permutation Sequence
    • Next Permutation
    • Kth Smallest Element in a BST
    • Word Search
    • Word Break
    • Shuffle an Array
    • Add Two Numbers
    • Longest Substring Without Repeating Characters
    • Longest Increasing Subsequence
    • 3Sum Smaller
    • LFU Cache
    • Copy List with Random Pointer
    • Linked List Cycle
    • Merge Sorted Array
    • Two Sum II - Input array is sorted
    • Search Insert Position
    • Find First and Last Position of Element in Sorted Array
    • Combination Sum
    • Path Sum
    • Roman to Integer
    • Valid Parentheses
    • Product of Array Except Self
    • Permutations
    • 3Sum
    • Reverse Integer
    • Longest Common Subsequence and substring
    • Implement Stack using Queues
    • Sort Characters By Frequency
    • Delete Node in a BST
    • Invert Binary Tree
    • Serialize and Deserialize BST
    • Reverse String
    • Binary Tree Zigzag Level Order Traversal
    • Friend Circles
    • Letter Combinations of a Phone Number
    • Fizz Buzz
    • Encode and Decode TinyURL
    • Binary Tree Right Side View
    • Shortest Word Distance III
    • Binary Search Tree Iterator
    • Kth Largest Element in an Array
    • Clone Graph
    • Lowest Common Ancestor III
    • Lowest Common Ancestor II
    • Reverse Words in a String
    • Path Sum
    • Find K Pairs with Smallest Sums
    • Validate Binary Search Tree
    • All O`one Data Structure
    • Top K Frequent Elements
    • Integer to Roman
    • Shortest Word Distance III
    • Edit Distance
    • Profitable Schemes
    • Minimum Window Substring
    • LRU Cache
    • Text Justification
    • Integer to English Words
    • Partition to K Equal Sum Subsets
    • Graph Valid Tree
    • Exclusive Time of Functions
    • Repeated DNA Sequences
    • Valid Number
    • Insert Delete GetRandom O(1)
    • Same Tree
    • Friends Within Three Jumps
    • Isomorphic Strings
    • Sum of Square Numbers
    • Valid Perfect Square
    • Evaluate Reverse Polish Notation
    • House Robber
    • Palindromic Substrings
    • Find Largest Value in Each Tree Row
    • Can Place Flowers
    • Insert Interval
    • Maximum Depth of Binary Tree
    • Two Sum
    • Paint House II
    • Max Points on a Line
    • Word Ladder II
    • Word Ladder
    • Validate IP Address
    • Maximum Product Subarray
    • Factor Combinations
    • Flatten Nested List Iterator
    • Max Stack
    • Number of Connected Components in an Undirected Graph
    • Combination Sum II
    • Permutations II
    • Permutations
    • Climbing Stairs
    • Paint House
    • Closest Binary Search Tree Value
    • Closest Binary Search Tree Value II
    • Rotate String
    • Max Area of Island
    • Maximum Subarray
    • Serialize and Deserialize Binary Tree
    • Second Minimum Node In a Binary Tree
    • Lowest Common Ancestor of a Binary Tree
    • Lowest Common Ancestor of a Binary Search Tree
    • Symmetric Tree
    • Binary Tree Upside Down
    • Maximum Depth of Binary Tree
    • Find Leaves of Binary Tree
    • Number of Islands
    • Nested List Weight Sum II
    • Nested List Weight Sum
    • Merge Intervals
    • Valid Triangle Number
    • Find K Closest Elements
    • Find Smallest Letter Greater Than Target
    • Pow(x,n)
    • Search in Rotated Sorted Array II
    • Search in Rotated Sorted Array
    • Sqrt(x)
    • Intersection of Two Linked Lists
    • Binary Tree Level Order Traversal
    • Shortest Word Distance
    • Two Sum III - Data structure design
    • Shortest Word Distance II
  • Binary Search
    • Find K Closest Elements
    • Find Min In Rotated Sorted Array
    • Find Peak Element
    • First Bad Version
    • First Position Of Target
    • Guess Num Higer Or Lower
    • Last Position Of Target
    • Longest Increasing Subsequence
    • Russian Doll Envelopes
    • Search In Big Sorted Array
    • Search Insert Position
    • Single Number IV
    • pow(x,n)
    • sqrt
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Search for a Range
    • Intersection of Two Arrays
    • Count of Smaller Numbers After Self
  • Binary Tree
    • 107. Binary Tree Level Order Traversal II
    • Lowest Common Ancestor of a Binary Tree
    • Lowest Common Ancestor of a Binary Tree II
    • Lowest Common Ancestor III
    • preorder Traversal
    • Inorder traversal
    • Binary Tree Path
    • post Order traversal
    • Level Traversal
    • Serialize and Deserialize Binary Tree 07/25
    • Find Leaves of Binary Tree 07/25
    • Sum of Left Leaves 07/25
    • Recover Binary Search Tree 07/26
    • Check Full Binary Tree 07/26
    • Binary Tree Longest Consecutive Sequence07/26
    • Equal Tree Partition 07/27
    • Same Tree 07/27
    • Sum Root to Leaf Numbers 07/26
    • Binary Search Tree Iterator 07/28
    • Preorder morris traversal 07/29
    • inorder traversal morris 07/29
  • BFS
    • Search Graph Nodes 07/30
    • Is Graph Bipartite? 07/30
    • Walls and Gates 07/30
    • Clone Graph 07/30
    • Word Ladder 07/30
    • Topological Sorting 08/01
    • Course Schedule 08/03
    • Course Schedule II 08/04
  • DFS
    • Target Sum 08/06
    • Minimum Subtree 08/07
    • Word Search 08/07
    • Pacific Atlantic Water Flow 08/08
    • Matrix Water Injection 08/10
    • Maximum Subtree 08/10
  • Dynamic Programming
    • 931. Minimum Falling Path Sum
    • Unique Binary Search Trees
  • Linked List
    • Reverse Linked List
    • Linked List Cycle
    • Swap Nodes in Pairs
    • Odd Even Linked List
    • Merge k Sorted Lists
    • Partition List
    • Palindrome Linked List
    • Reorder List
    • Linked List Cycle II
    • Delete Node in a Linked List
    • Reverse Nodes in k-Group
    • Rotate List
    • Reverse Linked List II
  • Arrays
    • 189. Rotate Array
    • 80. Remove Duplicates from Sorted Array II
    • 26. Remove Duplicates from Sorted Array
    • 628. Maximum Product of Three Numbers
    • 48. Rotate Image
    • 289. Game of Life
    • 334. Increasing Triplet Subsequence
    • 11. Container With Most Water
    • 122.Best Time to Buy and Sell Stock II
    • 274. H-Index
    • 134. Gas Station
    • 118. Pascal's Triangle
    • Sort Colors
    • Remove Element
    • Merge sorted array
    • First Missing Positive
  • Strings
    • 93. Restore IP Addresses
    • 71. Simplify Path
    • 43. Multiply Strings
    • 606. Construct String from Binary Tree
    • 917. Reverse Only Letters
    • 929.Unique Email Addresses
    • Valid Anagram
    • Compare Strings
    • Anagrams
    • Longest Common Prefix
    • Implement strStr()
    • String to Integer (atoi)
Powered by GitBook
On this page
  1. LinkedIn

Shortest Word Distance II

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: 3
Input: word1 = "makes", word2 = "coding"
Output: 1

Note: You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

这道题说要重复很多次调用,所以如果简单遍历的话,时间复杂度会很差,那么用hash map,把这个单词每次出现的地方存下来,然后在找到两个单词所有出现位置中的最小差就能找到,时间复杂度为O(MN),但是在遍历两个list的时候可以用two pointer来优化时间复杂度到O(N)

class WordDistance {
    
    
    public String[] words = null;
    
    public HashMap<String,List<Integer>> map = new HashMap<>();
    
    public WordDistance(String[] words) {
        for(int i = 0; i < words.length;i++){
            
            if(map.containsKey(words[i])){
                map.get(words[i]).add(i);
            }else{
                List<Integer> list = new ArrayList<>();
                list.add(i);
                map.put(words[i],list);
            }
        }
    }
    
    public int shortest(String word1, String word2) {
        if(word1 == null || word2 == null || !map.containsKey(word1) || !map.containsKey(word2)){
            return -1;
        }
        
        List<Integer> list1 = map.get(word1);
        List<Integer> list2 = map.get(word2);
        
        int res = Integer.MAX_VALUE;
        
        //for(int i : list1){
        //    for(int j : list2){
        //        res = Math.min(res,Math.abs(i - j));
        //    }
        //}
        
        int i =0, j = 0;
        while(i < list1.size() && j < list2.size()){
            int a = list1.get(i);
            int b = list2.get(j);
            
            res = Math.min(res,Math.abs(a - b));
            
            //找最小距离,所以尽可能缩小a和b的差距
            if(a < b)
                i++;
            if(a > b)
                j++;
        
        }
        
        
        return res;
        
    }
}

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance obj = new WordDistance(words);
 * int param_1 = obj.shortest(word1,word2);
 */

思路:

cz this question require many times calls. It means that if i just go through list every time. It is time consuming. What I am thinking is to record the word's location in the constructor, and everytime to query two word, just get the list of this two word's index and find the min distance.

犯错:res 应该设成int最大数,不然循环内比较时,res永远是0

map,containsKey, k要大写

空间复杂度 o(n),时间复杂度 o(n), query 时间复杂度 o(k),k max number of word1 or word2 numbers

class WordDistance {
    
    
    public Map<String, List<Integer>> map;
    
    public WordDistance(String[] words) {
        this.map = new HashMap<>();
        
        for(int i = 0; i < words.length;i++){
            if(!map.containsKey(words[i])){
                List<Integer> list = new ArrayList<>();
                
                list.add(i);
                map.put(words[i],list);
            }
            
            else{
                map.get(words[i]).add(i);
            }
        }
    }
    
    public int shortest(String word1, String word2) {
        if(!map.containsKey(word1) || !map.containsKey(word2)){
            return -1;
        }
        
        List<Integer> list1 = map.get(word1);
        List<Integer> list2 = map.get(word2);
        
        int res = Integer.MAX_VALUE;
        
        int i = 0, j = 0;
        
        while(i < list1.size() && j < list2.size() ){
            int a = list1.get(i);
            int b = list2.get(j);
            
            res = Math.min(res,Math.abs(a-b));
            
            if(a < b){
                i++;
            }else{
                j++;
            }
            
            
        }
        
        return res;
    }
}

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance obj = new WordDistance(words);
 * int param_1 = obj.shortest(word1,word2);
 */
PreviousTwo Sum III - Data structure designNextBinary Search

Last updated 6 years ago