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.

利用一个字典记录所有相同的字母的位置,然后就是两个有序数组比较最近的元素。

我设想把一个数组插入另一个数组,然后比较。C++ lower_bound大法。

class WordDistance {
private:
unordered_map<string,vector<int>> map;
public:
WordDistance(vector<string> words) {
for(int i=; i<words.size(); i++) map[words[i]].push_back(i);
} int shortest(string word1, string word2) {
vector<int> l1 = map[word1];
vector<int> l2 = map[word2];
int idx = ;
int ret = INT_MAX;
for(int i=; i<l2.size(); i++){
idx = lower_bound(l1.begin(), l1.end(),l2[i]) - l1.begin();
if(idx == l1.size()){
ret = min(ret, l2[i] - l1.back());
}else if(idx == ){
ret = min(ret, abs(l2[i] - l1.front()));
}else{
ret = min(ret, abs(l2[i] - l1[idx]));
ret = min(ret, abs(l2[i] - l1[idx-]));
}
if(ret == ) return ;
}
return ret;
}
};

下面是网上的简单做法,思路差不多,找最小的时候遍历,结果runtime24ms...

class WordDistance {
public:
unordered_map<string, vector<int> > map;
WordDistance(vector<string> words) {
for(int i = ; i < words.size(); i++){
map[words[i]].push_back(i);
}
}
int shortest(string word1, string word2) {
vector<int> v1, v2;
v1 = map[word1];
v2 = map[word2];
int diff = INT_MAX;
for(int i = ; i < v1.size(); i++)
for(int j = ; j < v2.size(); j++)
if(abs(v1[i]-v2[j]) < diff)
diff = abs(v1[i]-v2[j]);
return diff;
}
};

最新文章

  1. HTML5 input元素新的特性
  2. Windows 网络通讯开发
  3. Jmeter在linux上运行(命令行运行Jmeter)
  4. GCD 深入理解:第二部分
  5. 不使用配置文件动态注册HttpModule
  6. Java for LeetCode 062 Unique Paths
  7. Git使用详细教程
  8. hdu 2091 空心三角形
  9. perl /m
  10. react --- 搭建环境
  11. TCP建立连接三次握手和释放连接四次握手
  12. docker+gitlab+gitlab-runner部署
  13. python中类方法,实例方法,静态方法的作用和区别
  14. workman项目设置开机自启动
  15. Java NIO 与 IO之间的区别
  16. (转)linux用户态和内核态理解
  17. sqlplus命令手冊
  18. SQL Server 2008 R2数据库镜像部署图文教程
  19. JAVA之路(一)
  20. 【非root用户】安装【python,pip,package】

热门文章

  1. Windows问题
  2. Linux(CentOS)下编译安装apache
  3. kali工具的总结
  4. 九,configMap及secret的基本使用
  5. 8.2.ZooKeeper应用场景
  6. seq2seq keras实现
  7. linux内核 概念
  8. kubernetes(K8S)快速安装与配置集群搭建图文教程
  9. Storm实践(一):基础知识
  10. 14-SQLServer索引碎片