243. Shortest Word Distance

Given a list of words and two wordsword1andword2, return the shortest distance between these two words in the list.
For example,
Assume that words =["practice", "makes", "perfect", "coding", "makes"].
Givenword1=“coding”,word2=“practice”, return 3.
Givenword1="makes",word2="coding", return 1.
Note:You may assume thatword1does not equal toword2, andword1andword2are both in the list.

min的计算放到if里大大减少判断次数, 也提高了运行效率。

public int shortestDistance(String[] words, String word1, String word2) {
       int pos1 = -1;
       int pos2 = -1;
       int min = Integer.MAX_VALUE;
       for(int i = 0; i < words.length; i++){
                if(words[i].equals(word1)){
                       pos1 = i;
                       if(pos1 != -1 && pos2 != -1){
                               min = Math.min(min, Math.abs(pos1 - pos2));
                       }
                 }else if(words[i].equals(word2)){
                        pos2 = i;
                        if(pos1 != -1 && pos2 != -1){
                                  min = Math.min(min, Math.abs(pos1 - pos2));
                        }
                 }
       }
       return min;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • Given a list of words and two words word1 and word2, retu...
    AlanGuo阅读 3,276评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,769评论 19 139
  • Given a list of words and two words word1 and word2, retu...
    Jeanz阅读 1,781评论 0 0
  • 今天上午老师有事 所以我们就做了老师留的作业 感觉很好 自己做的程序和连接的硬件比较有成就感 还有最主要的事更能深...
    王春雪cs阅读 858评论 0 0