[LeetCode245] Shortest Word Distance III
2015-11-24 07:14
399 查看
This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2. Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. word1 and word2 may be the same and they represent two individual words in the list. For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. Given word1 = “makes”, word2 = “coding”, return 1. Given word1 = "makes", word2 = "makes", return 3. Note: You may assume word1 and word2 are both in the list. Hide Company Tags LinkedIn Hide Tags Array Hide Similar Problems (E) Shortest Word Distance (M) Shortest Word Distance II
这道题word1和2可能是一样的了,也就是duplicates之间的距离不是自己跟自己的距离。
然后就由II想到一个慢方法:O(n) time with O(n) memory;
class Solution { public: int shortestWordDistance(vector<string>& words, string word1, string word2) { //too slooow.... unordered_map<string, vector<int> > mp; for(int i = 0; i < words.size(); ++i) mp[words[i]].push_back(i); int pos1 = 0, pos2 = 0, minLen = INT_MAX; if(word1 != word2){ for(int i = 0; i<mp[word1].size(); ++i){ for(int j = 0; j< mp[word2].size(); ++j){ minLen = min(minLen, abs(mp[word1][i] - mp[word2][j])); } } }else{ for(int i = 1; i<mp[word1].size(); ++i){ minLen = min(minLen, abs(mp[word1][i] - mp[word1][i-1])); } } return minLen; } };
参考了大家的O(n) time w/ O(1) space, 太感慨了。。
class Solution { public: int shortestWordDistance(vector<string>& words, string word1, string word2) { int n = words.size(); int res = n, l = n, r = -n; for (int i=0; i<words.size(); i++) { if (words[i] == word1) l = (word1==word2)?r:i; if (words[i] == word2) r = i; res = min(res, abs(l-r)); } return res; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解