LeetCode 245. Shortest Word Distance III(最短单词距离)
2016-04-07 05:53
1021 查看
原题网址:https://leetcode.com/problems/shortest-word-distance-iii/
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 =
Given word1 =
return 1.
Given word1 =
return 3.
Note:
You may assume word1 and word2 are both in the list.
思路:对于word1==word2的情形单独处理,只需要用一个变量保存最近的位置。时间复杂度O(n),空间复杂度O(1)
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.
思路:对于word1==word2的情形单独处理,只需要用一个变量保存最近的位置。时间复杂度O(n),空间复杂度O(1)
public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { if (word1.equals(word2)) { int distance = Integer.MAX_VALUE; int current = -1; for(int i=0; i<words.length; i++) { if (word1.equals(words[i])) { if (current == -1) current = i; else { if (i-current < distance) distance = i-current;; current = i; } } } return distance; } else { int distance = Integer.MAX_VALUE; int pos1 = -1, pos2 = -1; for(int i=0; i<words.length; i++) { if (word1.equals(words[i])) { pos1 = i; if (pos2 != -1 && pos1-pos2<distance) distance = pos1-pos2; } else if (word2.equals(words[i])) { pos2 = i; if (pos1 != -1 && pos2-pos1<distance) distance = pos2-pos1; } } return distance; } } }
相关文章推荐
- The method getDispatcherType() is undefined for the type HttpServletRequest 升级到tomcat8(转)
- ios中的定时
- LeetCode 244. Shortest Word Distance II(最短单词距离)
- lintcode-easy-Ugly Number
- #8判断和循环#
- Xsolla 电子竞技学院合作项目正式启动:你加入了么?
- vs2015中升级Nuget后,找不到Umbraco安装包问题
- Windows的自带控件(比如TButton)大多数消息都由它自己处理,Delphi覆盖了那么多WM_函数优先级较低,一般用不上
- liunx 下scp出现 Permission denied, please try again 的解决办法
- Windows下Keras报错TypeError: <lambda>() got an unexpected keyword argument 'name'
- HttpClient
- Android属性动画
- swift 二维数组
- Nexus启动失败处理:The nexus service was launched, but failed to start.
- VB洗牌算法产生随机数组
- 五种情况下会刷新控件状态(刷新所有子FWinControls的显示)——从DFM读取数据时、新增加子控件时、重新创建当前控件的句柄时、设置父控件时、显示状态被改变时
- LeetCode 243. Shortest Word Distance(单词最短距离)
- Java发送邮件
- lintcode-medium-Subsets II
- 【AJAX】使用ajaxStart()和ajaxStop()方法