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里大大減少判斷次數(shù), 也提高了運(yùn)行效率。

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;
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • Given a list of words and two words word1 and word2, retu...
    AlanGuo閱讀 513評論 0 0
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,555評論 19 139
  • Given a list of words and two words word1 and word2, retu...
    Jeanz閱讀 290評論 0 0
  • 今天上午老師有事 所以我們就做了老師留的作業(yè) 感覺很好 自己做的程序和連接的硬件比較有成就感 還有最主要的事更能深...
    王春雪cs閱讀 138評論 0 0

友情鏈接更多精彩內(nèi)容