zoukankan      html  css  js  c++  java
  • LeetCode-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 = ["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.

    Solution:

    When word1==word2, update both p1 and p2 regularly and compute minDis for each update except when p2 updated and get p2==p1.

     1 public class Solution {
     2     public int shortestWordDistance(String[] words, String word1, String word2) {
     3         if (words.length<2) return -1;
     4     
     5         int p1 = -words.length, p2 = -words.length;
     6         int minDis = Integer.MAX_VALUE;
     7         for (int i=0;i<words.length;i++){
     8             if (!words[i].equals(word1) && !words[i].equals(word2)) continue;
     9 
    10             if (words[i].equals(word1)){
    11                 p1 = i;            
    12                 minDis = Math.min(minDis,Math.abs(p1-p2));
    13             } 
    14             
    15             if (words[i].equals(word2)){
    16                 p2 = i;
    17                 if (p2!=p1) minDis = Math.min(minDis,Math.abs(p1-p2));
    18             }
    19         }
    20         return minDis;
    21     }
    22 }
  • 相关阅读:
    RPC中阻塞队列的作用
    记用tensorflow-ranking时的bugs
    JDK作泛型比较时为什么把逻辑代码写两遍
    Java 不能声明泛型数组
    QuickSort Hoare vs Lomuto
    Java 对数组扩容
    Java交换两对象的问题
    毕业 失业
    dependencyManagement介绍
    web笔记
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5798952.html
Copyright © 2011-2022 走看看