zoukankan      html  css  js  c++  java
  • LC 244. Shortest Word Distance II 【lock, Medium】

    Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters. 

    Example:
    Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

    Input: word1 = “coding”, word2 = “practice”
    Output: 3
    
    Input: word1 = "makes", word2 = "coding"
    Output: 1

    Note:
    You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

    利用一个字典记录所有相同的字母的位置,然后就是两个有序数组比较最近的元素。

    我设想把一个数组插入另一个数组,然后比较。C++ lower_bound大法。

    class WordDistance {
    private:
        unordered_map<string,vector<int>> map;
    public:
        WordDistance(vector<string> words) {
          for(int i=0; i<words.size(); i++) map[words[i]].push_back(i);
        }
        
        int shortest(string word1, string word2) {
          vector<int> l1 = map[word1];
          vector<int> l2 = map[word2];
          int idx = 0;
          int ret = INT_MAX;
          for(int i=0; i<l2.size(); i++){
            idx = lower_bound(l1.begin(), l1.end(),l2[i]) - l1.begin();
            if(idx == l1.size()){
              ret = min(ret, l2[i] - l1.back());
            }else if(idx == 0){
              ret = min(ret, abs(l2[i] - l1.front()));
            }else{
              ret = min(ret, abs(l2[i] - l1[idx]));
              ret = min(ret, abs(l2[i] - l1[idx-1]));
            }
            if(ret == 0) return 0;
          }
          return ret;
        }
    };

    下面是网上的简单做法,思路差不多,找最小的时候遍历,结果runtime24ms...

    class WordDistance {
    public:
        unordered_map<string, vector<int> > map;
        WordDistance(vector<string> words) {
            for(int i = 0; i < words.size(); i++){
                map[words[i]].push_back(i);
            }
        }
        int shortest(string word1, string word2) {
            vector<int> v1, v2;
            v1 = map[word1];
            v2 = map[word2];
            int diff = INT_MAX;
            for(int i = 0; i < v1.size(); i++)
                for(int j = 0; j < v2.size(); j++)
                    if(abs(v1[i]-v2[j]) < diff)
                        diff = abs(v1[i]-v2[j]);
            return diff;
        }
    };
  • 相关阅读:
    线程安全好文章
    分布式事务
    jvm内存泄漏问题分析过程
    Java8--Lambda表达式
    ZK Watcher 的原理和实现
    JVM垃圾回收算法
    linux常用命令
    Excel常用函数汇总
    Debian 镜像使用帮助
    photon 下载地址
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10141026.html
Copyright © 2011-2022 走看看