[抄题]:

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.

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

[暴力解法]:

把word1所有的index存一个数组,把word2所有的index存一个数组,再i*j全部扫一遍

时间分析:n^2

空间分析:

[优化后]:

每次走一个index都随时更新一下i1 i2

时间分析:n

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

虽然不麻烦,但是Integer.MAX_VALUE 必须要存成long型,然后转回来就行了。不然会报错。

[思维问题]:

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

[二刷]:

[三刷]:

[四刷]:

[五刷]:

[五分钟肉眼debug的结果]:

[总结]:

p1 p2相等的时候,暂存一下之前的p2

if (word1.equals(word2))
//store in p1 temporarily
p1 = p2;
p2 = i;

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[算法思想:迭代/递归/分治/贪心]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

[代码风格] :

[是否头一次写此类driver funcion的代码] :

[潜台词] :

class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
//ini: p1, p2 into the long type
long result = Integer.MAX_VALUE;
long p1 = Integer.MAX_VALUE;
long p2 = -Integer.MAX_VALUE; //for loop: for each words[i], renew the answer
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) p1 = i;
if (words[i].equals(word2))
{
if (word1.equals(word2))
//store in p1 temporarily
p1 = p2;
p2 = i;
}
//renew the answer
result = Math.min(result, Math.abs(p2 - p1));
} //return
return (int)result;
}
}

最新文章

  1. [CentOS] 指定命令别名:Alias &amp; 软链接生成命令 ln -s
  2. 图形学理论知识 BRDF 双向反射分布函数(Bidirectional Reflectance Distribution Function)
  3. ganglia安装简记
  4. GCD详解
  5. [CF442B] Andrey and Problem (概率dp)
  6. bootstrap中的Tooltips工具提示的使用问题
  7. Atmega8型号细分区别
  8. 50个C++源码学习网站
  9. Command-line tools can be 235x faster than your Hadoop cluster
  10. php代码查询apache模块
  11. PCL点云库增加自定义数据类型
  12. 搭建ganglia集群而且监视hadoop CDH4.6
  13. python遍历字典元素
  14. 获取IIS版本
  15. 异常-----freemarker.core.InvalidReferenceException问题解决
  16. 提高UI设计效率的4个技巧
  17. SQL-55 分页查询employees表,每5行一页,返回第2页的数据
  18. 使用强类型DataSet增加数据并获取自动增长的ID
  19. 安装完MySQL数据库设置密码
  20. Mybatis注解开发模糊查询

热门文章

  1. torchvision里densenet代码分析
  2. 在Win10上使用Visual Studio2015的Android模拟器
  3. Keepalived+LVS实现高可用负载均衡双主模式
  4. Spring IOC 相关的面试题
  5. ElasticSearch的lowlevelApi和低级别API
  6. Html 页面载入内容前,显示 loading 效果。
  7. 利用STM32CubeMX来生成USB_HID_Mouse工程【添加ADC】(2)【非dma和中断方式】
  8. [转]SQL server2008 导入超大SQL脚本文件(超过10M)
  9. x86 asm调用框架(vs2015)
  10. 刘志梅201771010115.《面向对象程序设计(java)》第六周学习总结