• 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.

    Approach: two case:

    1: word1 != word2 , it is simple, some are using i1 = -1, i2 = -1 to check, here I used the distance. Because when checking the min distance, I dont want fake min distance in my result, so I try to expand the initial distance of i1 and i2 be greater than words.length, (but we also cannot use i1 = -1 and i2 = words.length, because the target word might give i2 = 0, then mindistance is 1, which is also fake)

    2: word1 == word2, the question becomes how to find the min distance of the indices of a single word. Such as "make" has indices of 0, 3, 5,xxxxx...how to find the min distance. Just use use current i minus last index and keep the global min value.

    may assume word1 and word2 are both in the list??????

    public int shortestWordDistance(String[] words, String word1, String word2) {
        if (words == null || words.length == 0) return 0;
        int i1 = -words.length;  //here is to guarantee mindistance will be greater than the word.length
        int i2 = words.length;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < words.length; i++) {
            if (!word1.equals(word2)) {
                if (words[i].equals(word1)) i1 = i;
                if (words[i].equals(word2)) i2 = i;
                min = Math.min(min, Math.abs(i1 - i2)); //so we don't have to check if (i1 != -1 && i2 != -1 in other solutions)
            } else {
                if (words[i].equals(word1)) {  //this the question on how to find the shortest distance of indices of the word
                    min = Math.min(min, Math.abs(i - i1));  //you can change to i - i1, it is also correct
                    i1 = i;  // update the i1 with current i for incoming distance checking
                }
            }
        }
        return min;
    }
    

      

      

  • 相关阅读:
    ERROR: Cannot set priority of registrydns process 33740
    Hbase和Phoenix部署-单机版
    ambari安装hdp时,新建的ambari-hdp-1.repo中baseurl无值
    centos7.2升级openssh到8.0
    kafka一个broker挂掉无法写入
    对cdh搭建过程错误总结及解决方法
    streamsets
    [Spark]Task not serializable
    [Kafka]How to Clean Topic data
    Postgresql Master/Slaver
  • 原文地址:https://www.cnblogs.com/apanda009/p/7797157.html
Copyright © 2020-2023  润新知